/****************************************
 * getMessageList 轮询接口
 * fetchOldMessageForService 获取客服历史消息
 * displayServiceMessageOnGetNewMessage 渲染客服消息
 * displayServiceMessageForStr 生成每条消息字符串模板
 * pushOneServiceMessage 发送消息
 * pushOneFAQTerm 未开启人工服务的时候发送消息自动推送匹配问题列表的答案
 * getConsultFAQ 获取常见问题列表
 * displayConsultFAQ 渲染常见问题列表
 * messageListScrollBottom 回到底部
 *
 * cookie
 * [id]_serviceMessageListData 历史消息存在这里
 */

var $checkOnlineUserIds = '',  // 要查询状态的房客id
	$checkOnlineUserCallback = ''; // 轮询是否在线的回调函数

var hasLoadLookNextPageData = true,      // 能否继续加载看看 做节流
	hasLoadnotifyNextPageData = true,    // 能否继续加载通知 做节流
	hasLoadCollectNextPageData = true;   // 能否继续加载我的收藏 做节流

var hasLoadSericeNextPageData = true;    // 能否继续加载和客服的聊天 做节流

var closeConsultTimer = null;//关闭会话计时器
(function ($) {

	var e = e ? e : window.event;

	$.fn.testWebim = function (options) {

		var defaults = {
			chatUserList: 0, //正常的等待循环标记
			chatUserList_wait: 0,   //1秒等待时间标记
			chatUserList_wait_num: 0,   //等待的次数（如果超过5次就直接进入正常查询）
			chatUserChat: 0,  //正常的等待循环标记
			chatUserChat_wait: 0,   //1秒等待时间标记
			chatUserChat_wait_num: 0,   //等待的次数（如果超过5次就直接进入正常查询）

			chatCurrentPage_wait: 0,  //进入页面就进行循环报名当前位置
			currentChatDelete_wait: 0, //进入页面就进行循环删除
			pushMessageNum: 0,   //发送的次数，如果过快，就给中断

            picture_host :'//cachezero.ciker360.com',


			checkOldServiceMessageSwitch: 0,//客服字段 这个是查询开关以防止查询多次
			//通过此状态判断页面是新打开的还是旧的页面(未用到)
			// checkOldServiceMessageStatus = 0;

			continueGetRoomList: true // 推荐房源分页加载
		};

		this.opts = $.extend({}, defaults, options);
		$.fn.extend(this, testWebim);


		this.init();
	}

	var testWebim = {
		/**初始化**/
		init: function () {
			var _this = this;
			// jQuery.cookie("openChatBoxMessageList",'true',{"expires":1,path:"/"});
			if (!$.cookie('ifOpenNow')) {
				$.cookie("ifOpenNow", 1, {path: "/"});
				store.clear();
			}

			var bodyWidth = $('body').width();
			if (bodyWidth >= 768) {
				if (jQuery.cookie("yyoh") && jQuery.cookie("id")) {

					//轮询
					_this.opts.chatUserList = window.setInterval(function(){_this.checkMessageList()},5000);

					//将当前页面的信息共享出去
					_this.opts.chatCurrentPage_wait = window.setInterval(function () {
						_this.sharePageInfo()
					}, 500);
					_this.opts.currentChatDelete_wait = window.setInterval(function () {
						_this.deletePageAndChatInfoForWhile()
					}, 2000);
					//进入页面就先渲染客服消息
					_this.displayServiceMessageOnPageInit();
				}
				//设定窗口显隐以及位置
				_this.setOverflowAndPosition();
				//注册监听动作(绑定事件)，已进入页面的时候就进行
				_this.registerMonitorAction();
				// 监听客服聊天部分
				_this.onDraggableFun('#serviceBoxDrggable');
			}


			//客服逻辑
			$(".content").mCustomScrollbar({
				mouseWheel: {preventDefault: true},
				callbacks: {
					onScroll: function () {
					},
					onScrollStart: function () {
						//在滚动时间开始的时候执行(字段isHavaOldServiceMessage是1的时候就展示等待框)
						var isHavaOldServiceMessage = store.get('isHavaOldServiceMessage');
						if (isHavaOldServiceMessage != 0) {
							$('.service-message-list-wait').show();
						}
					},
					onTotalScrollBack: function (e) {
						//滚动到顶部的时候调用
						_this.checkOldServiceMessageAction();

					},
					onTotalScroll: function (event) {
						//滚动到底部的时候调用
						//禁用滚动条

					}

				}
			});


			//点击"联系房东",打开聊天对话框
			_this.newChatForMe();

			//点击联系客服
			_this.onClickServiceBox();

			//发送给客服消息
			_this.pushOneServiceMessage();
			//点击"看看和通知",打开弹窗
			_this.onClickNotifyBox();
			//点击"我的收藏",打开弹窗
			_this.onClickCollectBox();
			//点击"意见反馈",打开弹窗
			_this.onClickfeedbackBox();
			// 点击聊天弹窗关闭按钮
			_this.onNoSessionListBtn();

			if ($.cookie("yyoh") && $.cookie("id")) {
				// 推荐房源
				_this.onInitRecommendHouse();
			}

		},


		/*
      * 将当前页面的信息共享出去
      */
		sharePageInfo: function () {

			var href = window.location.href;
			var timestamp = new Date().getTime();
			var chatCurrentPage = store.get('chatCurrentPage');
			if (!chatCurrentPage || chatCurrentPage == 'undefined') {
				//没有创建聊天列表存储器的时候
				var chatCurrentPage = [{
					page: href,
					time: timestamp
				}];
				store.set('chatCurrentPage', chatCurrentPage);
			} else {
				//更改控制器中本页面的时间信息
				var boo = true;
				for (var i = 0; i < chatCurrentPage.length; i++) {
					if (href == chatCurrentPage[i].page) {
						chatCurrentPage[i].time = timestamp;
						boo = false;
					}
				}
				//控制器中如果没有页面信息就添加一条新的信息进入
				if (boo) {
					var chatCurrentPage = store.get('chatCurrentPage');
					chatCurrentPage.push({
						page: href,
						time: new Date().getTime()
					});
				}
				store.set('chatCurrentPage', chatCurrentPage);
			}
		},

		/*
     * 循环删除存储其中以及聊天共享中的保费的信息
     * 存储器-deletePageAndChatInfoSwich  localstore中的数据 其中href：当前运行删除功能页面的路径  time：运行的最新时间
     */
		deletePageAndChatInfoForWhile: function () {
			var _this = this;
			var href = window.location.href;
			var timestamp = new Date().getTime();
			var deletePageAndChatInfoSwich = store.get('deletePageAndChatInfoSwich');
			//如果没有发现删除控制器就直接新建一个新建一个控制器
			if (!deletePageAndChatInfoSwich || deletePageAndChatInfoSwich == 'undefined') {
				var deletePageAndChatInfoSwich = {
					time: timestamp,
					href: href
				}
				store.set('deletePageAndChatInfoSwich', deletePageAndChatInfoSwich);
			} else {
				//如果控制器中是当前路径的就直接运行删除程序
				if (deletePageAndChatInfoSwich.href == href) {
					deletePageAndChatInfoSwich.time = timestamp;
					store.set('deletePageAndChatInfoSwich', deletePageAndChatInfoSwich);
					//直接运行删除函数
					_this.deletePageAndChatInfoAction();
				} else {
					if (timestamp - deletePageAndChatInfoSwich.time > 4000) {
						deletePageAndChatInfoSwich.time = timestamp;
						deletePageAndChatInfoSwich.href = href;
						store.set('deletePageAndChatInfoSwich', deletePageAndChatInfoSwich);
						//等不下去了，直接运行删除函数
						_this.deletePageAndChatInfoAction();
					}
				}
			}
		},

		/*
     * 根据控制器中的数据执行删除页面中多余数据
     * 存储器-chatCurrentPage 数组，每个数组包含当前页面的路径和更新时间
     */
		deletePageAndChatInfoAction: function () {
			//删除页面共享控制器
			var timestamp = new Date().getTime();
			var chatCurrentPage = store.get('chatCurrentPage');
			var chatCurrentPageTemp = [];
			if (chatCurrentPage) {
				for (var i = 0; i < chatCurrentPage.length; i++) {
					if (timestamp - chatCurrentPage[i].time < 1000) {
						chatCurrentPageTemp.push(chatCurrentPage[i]);
					}
				}
			}
			store.set('chatCurrentPage', chatCurrentPageTemp);
			//删除页面中的聊天共享信息
			var chatCurrentPage = store.get('chatCurrentPage');
			if (chatCurrentPage) {
				if (chatCurrentPage.length <= 1) {
					store.remove('chatCurrentPage');
				}
			} else {
				store.remove('chatCurrentPage');
			}
		},


		/*
     * 将获取到的数据设置给页面聊天窗口内
     */
		setMessageChat: function (houseId, userId_to, data) {
			try {

				var data_MessageList = data;
				if (data_MessageList) {

					var hasimgflag = 0;


					var _this = this;
					//正常的给当前页面填写数据
					var messageList = listSortBy(data_MessageList, 'publish_time', 'asc');


					for (var i = 0; i < messageList.length; i++) {
						if ($('#' + messageList[i].msgKey).length == 0) {
							var chatContent = '';

							var message = eval("(" + messageList[i].message + ")");
							chatContent = message.chatContent;
							if (chatContent) {
								chatContent = chatContent.replace(new RegExp("<", "g"), "&lt;");
								chatContent = chatContent.replace(new RegExp(">", "g"), "&gt;");
							}


							if (chatContent) {


                             if(messageList[i].messageType == '-2'){//有敏感词
                                 chatContent=chatContent.split($.i18n.prop('8f54f448ca6bb2f190652dbc95b0225a'))[0];
                             }

								var time = messageList[i].publish_time.substring(5, 19);
								var str = '';

								if (messageList[i].userId_from == userId_to) {
									str = '<p class="talk_time" aaaa id="' + messageList[i].id + '" style="display: block;">' + time + '</p>';
									if (messageList[i].messageType == '2') {
										str = str + '<div class="box message_pic" id="' + messageList[i].msgKey + '">\n\
                                        <div><img class="pic" src=' + chatContent + '?pt=1&st=large /></div>\n\
                                        <span></span>\n\
                                    </div>';

                                     hasimgflag++;
                                 }else if(message.recommendHouseId){
                                     var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                     var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                     var currency_symbol = currency_symbol_arr[message.userCurrency-1].symbol || '';
                                     str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                         '<div class="box white_bg pos_left" id="'+data_MessageList[i].msgKey+'">' +
                                         '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                         '<img src="'+message.recommendHousePicture+'"/>' +
                                         '<div class="houseInfo">' +
                                         '<p>'+message.recommendHouseTitle+'</p>' +
                                         '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') + '</p>' +
                                         '<p>'+currency_symbol+Math.round(message.userPrice)+'</p>' +
                                         '</div>' +
                                         '</a>' +
                                         '<span></span>' +
                                         '</div>'
                                 }
                                 else{
                                     str = str + '<div class="box" id="'+messageList[i].msgKey+'">\n\
                                        <div>'+chatContent+'</div>\n\
                                        <span></span>\n\
                                    </div>';
                                 }
                                 if(messageList[i].messageType == '-2'){
                                    str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                 }
                             }
                             else if(messageList[i].userId_to== userId_to){
                                 str = '<p class="talk_time" aaaato id="'+messageList[i].id+'" style="display: block;">'+time+'</p>';
                                 if(messageList[i].messageType == '2'){
                                     str = str + '<div class="box red_bg message_pic" id="'+messageList[i].msgKey+'">\n\
                                        <div><img class="pic" src='+chatContent+'?pt=1&st=large /></div>\n\
                                        <span></span>\n\
                                    </div>';

                                     hasimgflag++;
                                 }else if(message.recommendHouseId){
                                     var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                     var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                     var currency_symbol = currency_symbol_arr[message.recommendHouseCurrency-1].symbol || '';
                                     str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                         '<div class="box white_bg" id="'+data_MessageList[i].msgKey+'">' +
                                         '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                         '<img src="'+message.recommendHousePicture+'"/>' +
                                         '<div class="houseInfo">' +
                                         '<p>'+message.recommendHouseTitle+'</p>' +
                                         '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') + '</p>' +
                                         '<p>'+currency_symbol+Math.round(message.recommendHousePrice)+'</p>' +
                                         '</div>' +
                                         '</a>' +
                                         '<span></span>' +
                                         '</div>'
                                 }
                                 else{
                                     str = str + '<div class="box red_bg" id="'+messageList[i].msgKey+'">\n\
                                        <div>'+chatContent+'</div>\n\
                                        <span></span>\n\
                                    </div>';
									}

                                 if(messageList[i].messageType == '-2'){
                                     str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                 }
                             }
                             if(str){

									// insertDomforAfter(id,dom,parentDom)


									var $scrollbarbox = $('#chatcontentlistbox [scrollbartag="' + userId_to + '"]');
									if ($scrollbarbox.length > 0) {

										var $lastchild = $scrollbarbox.find('.mCustomScrollBox .mCSB_container .talk_time:last');
										if ($lastchild.length > 0) {
											var lastid = $lastchild.attr('id');
											if (lastid < messageList[i].id) {
												$scrollbarbox.children('.mCustomScrollBox').children('.mCSB_container').children('div').append(str);
											}
											else {
												insertDomforAfter(messageList[i].id, str, $scrollbarbox);
											}
										} else {
											$scrollbarbox.children('.mCustomScrollBox').children('.mCSB_container').children('div').append(str);
										}


									}


									// $('#scrollbar-msg-content-'+houseId+'-'+userId_to).children('.mCustomScrollBox').children('.mCSB_container').children('div').append(str);
									// $('#chatcontentlistbox [scrollbartag="'+userId_to+'"]').children('.mCustomScrollBox').children('.mCSB_container').children('div').append(str);


								}


							}

							//$('#chatcontentlistbox #scrollbar-msg-content-'+houseId+'-'+userId_to).mCustomScrollbar("scrollTo","bottom",{timeout:-10});

							$('#chatcontentlistbox [scrollbartag="' + userId_to + '"]').mCustomScrollbar("scrollTo", "bottom", {timeout: -10});


						}


					}


					if (hasimgflag > 0) {

						var $imgs = $('#chatcontentlistbox [scrollbartag="' + userId_to + '"]').find('.box img');
						//var $imgs=  $('#chatcontentlistbox #scrollbar-msg-content-'+houseId+'-'+userId_to).find('.box img'); 

						isImgLoad($imgs, function () {


							$('#chatcontentlistbox [scrollbartag="' + userId_to + '"]').mCustomScrollbar("scrollTo", "bottom", {timeout: -10});

							// $('#chatcontentlistbox #scrollbar-msg-content-'+houseId+'-'+userId_to).mCustomScrollbar("scrollTo","bottom",{timeout:-10});
						});

					}


				}


				//将其他页面发送的数据进行同步一下
				var sharePushMessageData = store.get('sharePushMessageData');
				if (sharePushMessageData) {
					if (sharePushMessageData.length > 0) {
						for (var i = 0; i < sharePushMessageData.length; i++) {
							var shareuserto = sharePushMessageData[i].house_user_to.split('-')[1];
							// var $houseuserto=$('#chatcontentlistbox #scrollbar-msg-content-'+sharePushMessageData[i].house_user_to);

							var $houseuserto = $('#chatcontentlistbox [scrollbartag="' + shareuserto + '"]');
							var $sharepushmessageid = $houseuserto.find('#' + sharePushMessageData[i].id);

							if ($sharepushmessageid.length <= 0) {
								var time = sharePushMessageData[i].publishTime.substring(5, 19);
								var str = '<p class="talk_time" bbbb id="' + sharePushMessageData[i].id + '" style="display: block;">' + time + '</p>';
								str = str + '<div class="box red_bg" id="' + sharePushMessageData[i].msgKey + '">\n\
                                    <div>' + sharePushMessageData[i].message + '</div>\n\
                                    <span></span>\n\
                                </div>';
								// var $scrollbar=$('#chatcontentlistbox #scrollbar-msg-content-'+sharePushMessageData[i].house_user_to);
								var $scrollbar = $('#chatcontentlistbox [scrollbartag="' + shareuserto + '"]');
								if ($scrollbar.length > 0) {
									if ($scrollbar.find('#' + sharePushMessageData[i].id).length <= 0) {

										// var $lastchild=$scrollbar.find('.mCustomScrollBox .mCSB_container .talk_time').filter('.talk_time:last');
										// if($lastchild.length>0){//如果原本有数据,则在id在最后一条数据之前的就不追加了,否则会造成信息错乱
										//     if(sharePushMessageData[i].id>$lastchild.attr('id')){
										//         console.log('追加 id:'+id);
										//         $scrollbar.children('.mCustomScrollBox').children('.mCSB_container').children('div').append(str);
										//         $scrollbar.mCustomScrollbar("scrollTo","bottom",{scrollInertia:500});
										//     }
										// }
										// else{
										//     $scrollbar.children('.mCustomScrollBox').children('.mCSB_container').children('div').append(str);
										//     $scrollbar.mCustomScrollbar("scrollTo","bottom",{scrollInertia:500});
										// }


										if (str) {
											insertDomforAfter(sharePushMessageData[i].id, str, $scrollbar);
										}

										$scrollbar.mCustomScrollbar("scrollTo", "bottom", {scrollInertia: 500});


									}
								}

							}
						}


					}
				}

				hasimgflag = 0;
				//将其他页面中获取的数据同步一下
				var shareGetMessageData = store.get('shareGetMessageData');
				if (shareGetMessageData) {
					if (shareGetMessageData.length > 0) {

						var param_userId = jQuery.cookie("id");
						for (var i = 0; i < shareGetMessageData.length; i++) {
							var str = '';
							// var $mCSB_container=$('#chatcontentlistbox #scrollbar-msg-content-'+shareGetMessageData[i].house_user_to).find('.mCustomScrollBox .mCSB_container');
							var shareuserto = shareGetMessageData[i].house_user_to.split('-')[1];
							var $mCSB_container = $('#chatcontentlistbox [scrollbartag="' + shareuserto + '"]').find('.mCustomScrollBox .mCSB_container');

							var $sharemessageid = $mCSB_container.find('#' + shareGetMessageData[i].id);

							if ($sharemessageid.length <= 0) {


								if (shareGetMessageData[i].userId_from == param_userId) {//发送的消息
									if (shareGetMessageData[i].messageType == '2') {

										str = str + '<p class="talk_time" cccc id="' + shareGetMessageData[i].id + '" style="display: block;">' + shareGetMessageData[i].publishTime.substring(5, 19) + '</p>\n\
                                                <div class="box red_bg message_pic" id="' + shareGetMessageData[i].msgKey + '">\n\
                                                    <div><img class="pic" src=' + shareGetMessageData[i].message + '?pt=1&st=large /></div>\n\
                                                    <span></span>\n\
                                                </div>';

                                     hasimgflag++;
                                 }else if(message.recommendHouseId){
                                     var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                     var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                     var currency_symbol = currency_symbol_arr[message.recommendHouseCurrency-1].symbol || '';
                                     str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                         '<div class="box white_bg" id="'+data_MessageList[i].msgKey+'">' +
                                         '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                         '<img src="'+message.recommendHousePicture+'"/>' +
                                         '<div class="houseInfo">' +
                                         '<p>'+message.recommendHouseTitle+'</p>' +
                                         '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') + '</p>' +
                                         '<p>'+currency_symbol+Math.round(message.recommendHousePrice)+'</p>' +
                                         '</div>' +
                                         '</a>' +
                                         '<span></span>' +
                                         '</div>'
                                 }else{
                                     str = str + '<p class="talk_time" dddd id="'+shareGetMessageData[i].id+'" style="display: block;">'+shareGetMessageData[i].publishTime.substring(5,19)+'</p>\n\
                                                <div class="box red_bg" id="'+shareGetMessageData[i].msgKey+'">\n\
                                                    <div>'+shareGetMessageData[i].message+'</div>\n\
                                                    <span></span>\n\
                                                </div>';
									}



                                 if(shareGetMessageData[i].messageType == '-2'){
                                     str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                 }


								}
								else {//收到别人发来的消息
									if (shareGetMessageData[i].messageType == '2') {
										str = str + '<p class="talk_time" eeee id="' + shareGetMessageData[i].id + '" style="display: block;">' + shareGetMessageData[i].publishTime.substring(5, 19) + '</p>\n\
                                            <div class="box message_pic" id="' + shareGetMessageData[i].msgKey + '">\n\
                                                <div><img class="pic" src=' + shareGetMessageData[i].message + '?pt=1&st=large /></div>\n\
                                                <span></span>\n\
                                            </div>';

                                     hasimgflag++;
                                 }else if(message.recommendHouseId){
                                     var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                     var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                     var currency_symbol = currency_symbol_arr[message.userCurrency-1].symbol || '';
                                     str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                         '<div class="box white_bg pos_left" id="'+data_MessageList[i].msgKey+'">' +
                                         '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                         '<img src="'+message.recommendHousePicture+'"/>' +
                                         '<div class="houseInfo">' +
                                         '<p>'+message.recommendHouseTitle+'</p>' +
                                         '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') + '</p>' +
                                         '<p>'+currency_symbol+Math.round(message.userPrice)+'</p>' +
                                         '</div>' +
                                         '</a>' +
                                         '<span></span>' +
                                         '</div>'
                                 }else{
                                     str = str + '<p class="talk_time" ffff id="'+shareGetMessageData[i].id+'" style="display: block;">'+shareGetMessageData[i].publishTime.substring(5,19)+'</p>\n\
                                            <div class="box" id="'+shareGetMessageData[i].msgKey+'">\n\
                                                <div>'+shareGetMessageData[i].message+'</div>\n\
                                                <span></span>\n\
                                            </div>';
									}



                                 if(shareGetMessageData[i].messageType == '-2'){
                                     str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                 }
                             }


								if (str) {//倒序插入数据

									//var $scrollbar=$('#chatcontentlistbox #scrollbar-msg-content-'+shareGetMessageData[i].house_user_to);

									var $scrollbar = $('#chatcontentlistbox [scrollbartag="' + shareuserto + '"]');


									if ($scrollbar.length > 0) {
										if ($scrollbar.find('#' + shareGetMessageData[i].id).length <= 0) {

											if (str) {
												insertDomforAfter(shareGetMessageData[i].id, str, $scrollbar);
											}


											// $scrollbar.children('.mCustomScrollBox').children('.mCSB_container').children('div').prepend(str);
											$scrollbar.mCustomScrollbar("scrollTo", "bottom", {scrollInertia: 500});

										}
									}

								}

							}
						}


					}
				}


			}
			catch (e) {
				console.log(e);
			}


		},

		/*
     * 5秒的长轮询查询聊天列表(聊天列表,聊天内容合并)
     */
		checkMessageList: function (houseId, userId_to) {
			var _this = this;
			var timestamp = new Date().getTime();
			if (!houseId || !userId_to) {
				houseId = '';
				userId_to = '';
			}

			var houseMessageListSwitch = store.get('houseMessageListSwitch');
			var houseMessageListData = store.get('houseMessageListData');

			var houseMessageChatSwitch = store.get('houseMessageChatSwitch');
			var houseMessageChatData = store.get('houseMessageChatData');

			if (!houseMessageListSwitch || houseMessageListSwitch == 'undefined') {
				//没有创建聊天列表存储器的时候
				store.set('houseMessageChatSwitch', {switch: 1, time: timestamp, num: 0});
				// _this.getMessageChat(timestamp,houseId,userId_to);

				store.set('houseMessageListSwitch', {switch: 1, time: timestamp, num: 0});


				_this.getMessageList(timestamp, houseId, userId_to);

			} else {

				if (timestamp - houseMessageListSwitch.time > 4900) {
					//这里由于存在时间间隔很小的时候，所以在此查询控制器数据

					//如果大于5000秒了
					if (houseMessageListSwitch.switch == 1) {
						//如果被锁了，就停止5秒循环，进行1秒循环重查知道第五次还是查不到数据就进行后续的5秒重查
						window.clearInterval(_this.opts.chatUserList);
						//启动五次1秒的等待
						_this.opts.chatUserList_wait = window.setInterval(function () {
							_this.checkMessageListForWait(houseId, userId_to)
						}, 1000);
					} else {

						if (houseMessageListSwitch.switch == 1) {
							//如果被锁了，就停止5秒循环，进行1秒循环重查知道第五次还是查不到数据就进行后续的5秒重查
							window.clearInterval(_this.opts.chatUserList);
							//启动五次1秒的等待
							_this.opts.chatUserList_wait = window.setInterval(function () {
								_this.checkMessageListForWait(houseId, userId_to)
							}, 1000);
						} else {


							var myDate = new Date();
							//锁定控制器，进行下一步的查找
							houseMessageListSwitch.switch = 1;
							houseMessageListSwitch.time = timestamp;


							store.set('houseMessageListSwitch', houseMessageListSwitch);
							_this.getMessageList(timestamp, houseId, userId_to);
							// _this.getMessageList(timestamp);
						}
					}
				} else {

					//如果小于5秒就去直接拿存储的数据
					var houseMessageListData = store.get('houseMessageListData');

					_this.setLastHouseMessage(houseMessageListData);


					//如果小于5秒就去直接拿存储的数据
					// var houseMessageChatData = store.get('houseMessageChatData');
					// _this.setMessageChat(houseId,userId_to,houseMessageChatData);
				}
			}
			//判断cookie中存储的页面开关是否打开，如果打开了就直接打开窗口
			_this.setOverflowAndPosition();
		},

		/*
     * 短轮询等待1秒钟的等待
     */
		checkMessageListForWait: function (houseId, userId_to) {
			var _this = this;
			//将次数+1，如果超过5次就直接进入正常查询
			_this.opts.chatUserList_wait_num++;
			if (_this.opts.chatUserList_wait_num > 5) {
				if (currentAjax) {
					currentAjax.abort();
					currentAjax = 0;
				}
				//将循环记录清空
				_this.opts.chatUserList_wait_num = 0;

				//将控制器开关关闭
				var houseMessageListSwitch = store.get('houseMessageListSwitch');


				houseMessageListSwitch.switch = 0;
				store.set('houseMessageListSwitch', houseMessageListSwitch);

				//结束一秒等待
				window.clearInterval(_this.opts.chatUserList_wait);
				//进入正常等待
				_this.opts.chatUserList = window.setInterval(function () {
					_this.checkMessageList(houseId, userId_to)
				}, 5000);
			} else {
				//进行查询是否被解锁，如果解锁就接触等待，继续常规循环
				var houseMessageListSwitch = store.get('houseMessageListSwitch');


				//如果被解锁，就直接结束1秒循环进入正常的5秒等待
				if (houseMessageListSwitch.switch == 0) {
					//结束一秒等待
					window.clearInterval(_this.opts.chatUserList_wait);
					//进入正常等待
					_this.opts.chatUserList = window.setInterval(function () {
						_this.checkMessageList(houseId, userId_to)
					}, 5000);
					//直接拿存储的数据
					var houseMessageListData = store.get('houseMessageListData');
					_this.setLastHouseMessage(houseMessageListData);
				}
			}
		},

		/*
     * 查询聊天信息，如果存储器中的值和传入的值不一样，就直接抛弃此数据
     * checktime 发起查询的时候的数据
     */
		getMessageList: function (checktime, houseId, userId_to, fn) {
			var _this = this;

			var data_control = $('.im_list_ul').attr('data-control');
			//如果和控制台一样就继续查询，如果控制台的编码变换了就不传houseId和userId_to
			if (data_control != houseId + '-' + userId_to) {
				houseId = '';
				userId_to = '';

			}
			if (!userId_to) {//聊天对象为空时,检测聊天列表的选中数据(打开页面时使用)
				var $listbg = $('.im_list_ul');
				if ($listbg.length > 0) {
					var datacontrol = $listbg.attr('data-control');
					if (datacontrol) {
						datacontrol = datacontrol.split('-')[1];
						userId_to = datacontrol;
					}

				}


			}

			var msgId = 0;
			if (houseId && userId_to) {
				var $msgcontent = $('#msg-content-' + houseId + '-' + userId_to);
				if ($msgcontent.is(':visible')) {
					var $lasthistory = $msgcontent.find('.talk_time:last');
					if ($lasthistory.length > 0) {
						msgId = $lasthistory.attr('id');
					}
					else {//如果是打开窗口,则获取不到可见的container,取当前选中的对话的对话框的是后一条
						var $list_bg = $('.im_list_ul .list_bg');
						if ($list_bg.length > 0) {
							if ($list_bg.attr('userto') == userId_to) {

								var id = $list_bg.attr('id');
								id = id.split('plug-chat-')[1];
								var $curmsgcontent = $('.msg-content[id=msg-content-' + id + ']');
								if ($curmsgcontent.length > 0) {
									$curlastli = $curmsgcontent.find('.mCSB_container').find('.talk_time:last');
									if ($curlastli.length > 0) {
										msgId = $curlastli.attr('id');
									}

								}
							}


						}

					}
				}
			}


			var param = {};
			param.yyoh = $.cookie("yyoh");
			param.userId = $.cookie("id");

			param.isTestApi = '';//值为1时表示数据桩
			param.userId_to_id = userId_to;//聊天对象的id
			param.msgId = msgId;//聊天记录开始id
			param.checkOnlineUserIds = $checkOnlineUserIds;

			var serviceMessageBoxIsShow = store.get('serviceMessageBoxIsShow');

			var value = JSON.stringify(param);

			var getflag = false;


			try {
				treatData('pushMessage/getSessionList', value, function (data, url) {

					if (data.status.status_code == 0) {//说明请求接口成功
						getflag = true;
						// 轮询是否在线的回调函数
						if ($checkOnlineUserCallback) {
							$checkOnlineUserCallback(data)
						}
					}

					//将当前页面获取的消息存入临时存储器中，以便共享到其他页面中使用
					var chatCurrentPage = store.get('chatCurrentPage');
					if (chatCurrentPage) {
						if (chatCurrentPage.length > 1) {//有一个窗口就存储,方便后来打开的窗口取数据
							var shareGetMessageData = store.get('shareGetMessageData');
							if (!shareGetMessageData || shareGetMessageData == 'undefined') {
								//没有共享数据的时候
								shareGetMessageData = [];
							}
							//有共享数据的时候
							if (data.status.status_code == 0) {
								if (data.result.OneSession.length > 0) {
									for (var k = 0; k < data.result.OneSession.length; k++) {
										var chatContent = '';
										var message = '';
										try {
											message = eval("(" + data.result.OneSession[k].message + ")");
										}
										catch (e) {
											message = '';
										}

										if (message) {
											chatContent = message.chatContent;
											if (chatContent) {
												chatContent = chatContent.replace(new RegExp("<", "g"), "&lt;");
												chatContent = chatContent.replace(new RegExp(">", "g"), "&gt;");

												shareGetMessageData.push({
													id: data.result.OneSession[k].id,
													msgKey: data.result.OneSession[k].msgKey,
													messageType: data.result.OneSession[k].messageType,
													publishTime: data.result.OneSession[k].publish_time,
													house_user_to: data.result.OneSession[k].houseId + '-' + data.result.OneSession[k].userId_to,
													userId_from: data.result.OneSession[k].userId_from,
													message: chatContent,
													saveTime: new Date().getTime()
												});
											}

										}

									}
								}
							}
							store.set('shareGetMessageData', shareGetMessageData);
						} else {
							//直接删除全部存储的历史聊天记录
							store.remove('shareGetMessageData');
						}
					}

					//正常处理数据
					if (checktime) {
						if (data.status.status_code == 0 || data.status.status_code == 60005) {
							var switcharr = store.get('houseMessageChatSwitch');
							//如果存储器中的值和传入的值不一样，就直接抛弃此数据
							if (switcharr.time == checktime) {
								switcharr.switch = 0;
								switcharr.num = switcharr.num + 1;
								store.set('houseMessageChatSwitch', switcharr);
								store.set('houseMessageChatData', data.result.OneSession);
								if ($.cookie("openedchatbox") == 1)
									_this.setMessageChat(houseId, userId_to, data.result.OneSession);
							}
						}
					} else {
						//直接查询的时候，例如点击切换聊天对象，需要快速查找聊天消息
						if ($.cookie("openedchatbox") == 1)
							_this.setMessageChat(houseId, userId_to, data.result.OneSession);
					}


					if (data.status.status_code == 0) {



						//存储客服聊天系统(?)
						// if(!data.consultMessage.length)data.consultMessage=[];
						// if(!data.consultSendMessage.length)data.consultSendMessage=[];
						// data.allConsultMessage = data.consultMessage.concat(data.consultSendMessage);
						var OneConsult = data.result.OneConsult;
						OneConsult.sort(function(obj1, obj2){
							return obj1.id-obj2.id;
						});

						if (OneConsult.length) {
							OneConsult = listSortBy(OneConsult, 'publish_time', 'asc');

							// store.set($.cookie("id")+'_serviceMessageListNum', OneConsult.length);

							store.set($.cookie("id") + '_serviceMessageListNum', data.result.consultUnreadNum);

							//如果有聊天数据,就存储起来
							if (data.result.OneConsult.length > 0 && serviceMessageBoxIsShow == 1) {
								if (data.result.consultUnreadNum > 0) {
									if ($('.service-box').css('display') == 'block') {
										_this.setServiceMessageRead(OneConsult, 'getService');
									}

								}


								//将消息储存下来
								store.set($.cookie("id") + '_serviceMessageListNewData', OneConsult);
							} else {
								//没有数据就储存为空的
								store.set($.cookie("id") + '_serviceMessageListNewData', []);
							}

						}


						if (checktime) {
							var switcharr = store.get('houseMessageListSwitch');
							//如果存储器中的值和传入的值不一样，就直接抛弃此数据

							if (switcharr) {
								if (switcharr.time == checktime) {
									switcharr.switch = 0;
									switcharr.num = switcharr.num + 1;

									store.set('houseMessageListSwitch', switcharr);
									store.set('houseMessageListData', data);


									// if(!houseId||!userId_to)
									_this.setLastHouseMessage(data);
								}
							}

						} else {
							//没有传时间的情况下，直接用获取的数据，不进行存储
							// if(!houseId||!userId_to)
							_this.setLastHouseMessage(data);
						}


					} else {


						window.clearInterval(_this.opts.chatUserList);
						//未登录的时候
					}

					fn && fn(data);

				});
			}
			catch (e) {
				if (!getflag)//请求接口失败,重新开始轮询
					store.remove('houseMessageListSwitch');
			}

		},

		/*
     * 将获取的消息列表放入box中
     */
		setLastHouseMessage: function (data) {
			var _this = this;
			// if(!data.result.SessionList) {
			//     $('#IM-Chatwin').hide();
			//     $('#messlist-box').show();
			// } else {
			//     $('#IM-Chatwin').show();
			//     $('#messlist-box').hide();
			// }
			// console.log('进行客服聊天的渲染,嘎嘎');
			//如果客服聊天窗口打开的状态就直接渲染新的数据
			//这里进行渲染
			_this.displayServiceMessageOnGetNewMessage();
			//旧的历史消息也渲然
			_this.displayServiceMessageForOldMessage();
			//如果存储中的是1,就直接打开窗口
			var serviceMessageBoxIsShow = store.get('serviceMessageBoxIsShow');
			if (serviceMessageBoxIsShow == 1) {
				if ($('.service-box').css('display') == 'none') {  // 修复间隔5s滚动到最新消息bug
					$('.service-box').show();
					_this.messageListScrollBottom();
				}
			} else {
				$('.service-box').hide();
			}

			var oldindex = '';

			if (!data)
				return;


			if (data.result.consultUnreadNum > 0) {//客服
				$('#unreadServiceCount').show().html(data.result.consultUnreadNum);
			} else {
				$('#unreadServiceCount').hide().html('');
			}

			//通知 和 看看 的未读表示
			if (data.result.unReadArticleNum > 0 || data.result.unReadNotificationNum > 0) {
				var unReadArticleNum = parseInt(data.result.unReadArticleNum) > 99 ? '99+' : data.result.unReadArticleNum;  // 看看
				var unReadNotificationNum = parseInt(data.result.unReadNotificationNum) > 99 ? '99+' : data.result.unReadNotificationNum; // 通知
				// 通知的未读数目
				if (data.result.unReadArticleNum > 99) {
					$('#lookBtnNum').css({
						'width': '28px',
						'height': '19px',
						'line-height': '18px',
						'border-radius': '12px',
						'right': '-5px',
						'top': '15px'
					});
					$('#lookBtnNum').html(unReadArticleNum).show().parent().show();
				} else if (data.result.unReadArticleNum > 0) {
					$('#lookBtnNum').css({
						'width': '19px',
						'height': '19px',
						'line-height': '19px',
						'border-radius': '50%',
						'right': '-5px'
					});
					$('#lookBtnNum').html(unReadArticleNum).show().parent().show();
				} else {
					$('#lookBtnNum').hide().html('');
				}

				// 看看的未读数目
				if (data.result.unReadNotificationNum > 99) {
					$('#notifyBtnNum').css({
						'width': '28px',
						'height': '19px',
						'line-height': '18px',
						'border-radius': '12px',
						'right': '-5px',
						'top': '15px'
					});
					$('#notifyBtnNum').html(unReadNotificationNum).show().parent().show();
				} else if (data.result.unReadNotificationNum > 0) {
					$('#notifyBtnNum').css({
						'width': '19px',
						'height': '19px',
						'line-height': '19px',
						'border-radius': '50%',
						'right': '-5px'
					});
					$('#notifyBtnNum').html(unReadNotificationNum).show().parent().show();
				} else {
					$('#notifyBtnNum').hide().html('');
				}

				// 通知和看看的未读总数
				var unreadLookNotifyCountNum = parseInt(data.result.unReadArticleNum) + parseInt(data.result.unReadNotificationNum);
				if (unreadLookNotifyCountNum > 99) {
					$('#unreadLookNotifyCount').css({
						'width': '28px',
						'height': '19px',
						'line-height': '18px',
						'border-radius': '12px',
						'right': '-5px',
						'top': '-7px'
					});
				} else {
					$('#unreadLookNotifyCount').css({
						'width': '19px',
						'height': '19px',
						'line-height': '19px',
						'border-radius': '50%',
						'right': '-5px'
					});
				}
				unreadLookNotifyCountNum = unreadLookNotifyCountNum > 99 ? '99+' : unreadLookNotifyCountNum;
				$('#unreadLookNotifyCount').html(unreadLookNotifyCountNum).show().parent().show();


			} else {
				$('#unreadLookNotifyCount').hide().html('');
			}


			//设置未读或已读标识(右下角按钮)
			if (data.result.unreadCount > 0) {

				var unreadcount = parseInt(data.result.unreadCount) > 99 ? '99+' : data.result.unreadCount;
				if (data.result.unreadCount > 99) {
					$('#unreadCount').css({
						'width': '28px',
						'height': '19px',
						'line-height': '18px',
						'border-radius': '12px',
						'right': '-5px',
						'top': '-7px'
					});
				} else {
					$('#unreadCount').css({
						'width': '19px',
						'height': '19px',
						'line-height': '19px',
						'border-radius': '50%',
						'right': '-5px'
					});
				}
				$('#unreadCount').html(unreadcount).show().parent().show();


			} else {
				$('#unreadCount').hide().html('');
			}

			// ---- 2017/7/1 如果返回的sessionList 里面没有数据,就是没有和别人聊过天,则显示空白聊天弹窗
			// hasMessageList 为TRUE 的时候是有聊天列表  false没有聊天列表显示空白弹窗
			if (!data.result.SessionList.length) {

				jQuery.cookie("hasMessageList", '', {"expires": 1, path: "/"});

				// if($('.im_L.im_M.im_new_L.im_new_M.im_new_hover').hasClass('open')) {
				//     $('#messlist-box').show();
				//     $('#IM-Chatwin').hide();
				//     $('.look-notify-items-box').hide();
				//     $('.look-collect-box').hide();
				//     $('.look-feedback-box').hide();
				//     $('.im_L.im_new_L.im_new_hover').removeClass('open');
				//     $('.im_L.im_new_L.im_new_M.im_new_hover').addClass('open');
				//     // _this.onNoSessionListBtn();
				// } else {
				//     $('#messlist-box').hide();
				// }
			} else {
				jQuery.cookie("hasMessageList", 'true', {"expires": 1, path: "/"});
			}

			if ($.cookie("openedchatbox") != 1)
				return;


			var existIm = [];
			var checkArr = [];
			var j = 0;
			var MessageList = data.result.SessionList;

			for (var i = MessageList.length - 1; i >= 0; i--) {
				//判断接口给重复数据的情况下，删掉重复的数据
				var boo = false;
				for (var j = 0; j < existIm.length; j++) {
					var exits = existIm[j].houseId + '-' + existIm[j].userId_to_id;
					var current = MessageList[i].houseId + '-' + MessageList[i].userId_to_id
					if (exits == current) {
						boo = true;
					}
				}
				if (boo) {
					break;
				}
				//正常保存数据
				var userId_to_id = MessageList[i].userId_to_id;
				var nickName = MessageList[i].userId_to_nickName;
				var headUrl = MessageList[i].userId_to_url;
				var readYN = '';
				var readNo = '';
				if (MessageList[i].unreadMsgCount > 0) {
					readYN = 'unreadCount';
					readNo = MessageList[i].unreadMsgCount;
				}
				var attr = {
					"nickName": nickName,
					"userId_to_id": userId_to_id,
					"userId": jQuery.cookie("id"),
					"houseId": MessageList[i].houseId,
					"headUrl": headUrl,
					"readYN": readYN,
					"readNo": readNo,
					"publish_time": MessageList[i].chatSendTime,
					"survival": ''
				};
				checkArr[j++] = MessageList[i].houseId + '-' + userId_to_id;
				existIm.push(attr);
			}

			var new_chat = [];
			if (jQuery.cookie("temporary_chat")) {
				var old_chat = jQuery.cookie("temporary_chat");
				var chatArr = JSON.parse(old_chat);
				for (var i = 0; i < chatArr.length; i++) {
					//判断是否过期
					var survival = chatArr[i].survival;
					var nowTime = new Date().getTime();
					if (survival > nowTime) {
						var hasexit = false;

						var attr = {
							"nickName": chatArr[i].nickName,
							"userId_to_id": chatArr[i].userId_to_id,
							"userId": chatArr[i].userId,
							"houseId": chatArr[i].houseId,
							"headUrl": chatArr[i].headUrl,
							"readYN": chatArr[i].readYN,
							"readNo": chatArr[i].readNo,
							"publish_time": chatArr[i].publish_time,
							"survival": chatArr[i].survival
						};

						for (var j = 0; j < existIm.length; j++) {
							if (chatArr[i].userId == existIm[j].userId && chatArr[i].userId_to_id == existIm[j].userId_to_id) {
								//临时聊天和返回的聊表列表有重复,只是房源不一致
								if (chatArr[i].houseId != existIm[j].houseId) {
									hasexit = true;
									existIm[j].houseId = chatArr[i].houseId;

									// existIm.splice(j,1);
									// existIm.insert(j,attr);
									break;
								}
							}
						}

						if (!hasexit) {

							if (chatArr[i].userId == jQuery.cookie("id")) {
								if (!in_array(checkArr, chatArr[i].houseId + '-' + chatArr[i].userId_to_id)) {
									existIm.push(attr);
									new_chat.push(attr);
								}
							} else {

								new_chat.push(attr);
							}
						}


					}
				}
				if (new_chat.length > 0) {
					var temporary = JSON.stringify(new_chat);
					jQuery.cookie("temporary_chat", temporary, {"expires": 1, path: "/"});
				} else {
					jQuery.cookie("temporary_chat", null, {"expires": -1, path: "/"});
				}
			}
			//给数组进行排序
			var chatList = listSortBy(existIm, 'publish_time', 'desc');
			//设置左侧的人员聊天选中状态
			var house_user_to = '';
			if (chatList[0]) {
				house_user_to = chatList[0].houseId + '-' + chatList[0].userId_to_id;
			}

			var tag = false;
			var deleteAlready = true;
			var temporary_house_user_to = '';
			if (jQuery.cookie("chatwin_house_user_to")) {
				//如果cookie中有，但是列表中没有，就证明被中途删掉了，重新选择选中状态
				temporary_house_user_to = jQuery.cookie("chatwin_house_user_to");
				tag = true;
			} else {
				jQuery.cookie("chatwin_house_user_to", house_user_to, {path: "/"});
			}
			var $imlistul = $('.im_list_ul');
			var $li = $imlistul.find('li');
			var len = $li.length;


			var otherpagesflag = false;


			if (len > 0) {//原本就有数据
				var $listbg = $imlistul.find('.list_bg');
				oldindex = $listbg.index();
				var str = '';
				var circle = 0;//循环次数标识

				for (var k = 0; k < len; k++) {//同步已删除的聊天对象
					var $this = $li.eq(k);

					var id = $this.attr('id');

					var deleted = true;
					for (var c in chatList) {
						if (id.split('-')[3] == chatList[c].userId_to_id) {
							deleted = false;
							break;
						}
					}
					if (deleted) {
						$this.remove();
					}
				}

				for (var i = 0; i < chatList.length; i++) {


					var ifhasdom = false;//这一条数据原本就在会话中的标识,默认为false
					if (tag) {
						if ((temporary_house_user_to == chatList[i].houseId + '-' + chatList[i].userId_to_id) || (temporary_house_user_to.split('-')[1] == chatList[i].userId_to_id)) {
							deleteAlready = false;
						}
					}

					for (var j = 0; j < len; j++) {//不能用each,each后执行
						var $this = $li.eq(j);

						var id = $this.attr('id');

						var chatlistliid = 'plug-chat-' + chatList[i].houseId + '-' + chatList[i].userId_to_id;

						var newinfoflag = false;//原来是否就有新消息的标识

						//if(chatlistliid==id){
						if ($this.attr('userto') == chatList[i].userId_to_id) {

							//如果房源换了,则设个房源标识

							if ($this.attr('lihouseid') != chatList[i].houseId) {


								$this.attr('newhouseid', chatList[i].houseId);
							}

							// else{
							//     $this.removeAttr('newhouseid');
							//     console.log('删除newhouseid');
							// }


							ifhasdom = true;
							$this.attr('curexitflag', 'true');//如果当前对象也在新来的数据列表中,则设个标识,没有这个标识的元素要删除掉
							var $closespan = $this.find('.close');

							if ($closespan.hasClass('unreadCount')) {//原本就有未读消息
								if (chatList[i].readNo == 0 && !chatList[i].readYN) {//如果原本有未读的,但其他端将其设为已读了
									$closespan.hide().find('span').html('');
								}
								else if (chatList[i].readNo > 0 && chatList[i].readYN) {
									var readno = parseInt(chatList[i].readNo) > 99 ? 99 : chatList[i].readNo;
									$closespan.show().find('span').html(readno);
								}
							} else {
								if (chatList[i].readNo > 0 && chatList[i].readYN) {
									if ($listbg.attr('userto') != chatList[i].userId_to_id)//如果原本这个对话就是当前聊天对象,则不必写了,因为还要设置成已读
									{
										var readno = parseInt(chatList[i].readNo) > 99 ? 99 : chatList[i].readNo;

										$closespan.show().addClass(chatList[i].readYN).find('span').html(chatList[i].readNo);
										newinfoflag = true;//说明这个会话对象有新消息过来,要置顶的
									}
									else {
										//把当前聊天对象的未读信息设置为已读
										_this.notifyOneSessionHasReadToServer($listbg.attr('userto'));//把当前会话对象的消息设置为已读
										newinfoflag = true;//说明这个会话对象有新消息过来,要置顶的
									}
								}

							}

						}


						if (chatList[i].readNo > 0 && chatList[i].readYN) {//如果有未读消息,且未读消息是未读状态
							if (chatlistliid == id) {
								if ($this.hasClass('list_bg') && j != 0)//如果这个对象是当前聊天对象,且没有在最前端,则让这个对象移到最前面,且设置滚动条滚动位置为最上面
								{
									if (newinfoflag) {//有新消息来
										//置顶(仅前端,没有存到数据库)
										var tempobj = $this.clone(true);
										$this.remove();
										$imlistul.prepend(tempobj);


										//以下是设置滚动条
										$('#im_ul_wrapper').mCustomScrollbar("scrollTo", 'top', {scrollInertia: 50});
										$.cookie("ulscrolltop", ('0px'), {"expires": 1, path: "/"});

										var im_list_ulscrolltop = $.cookie("im_list_ulscrolltop");
										if (im_list_ulscrolltop) {
											$.cookie("im_list_ulscrolltop", ('0px'), {"expires": 1, path: "/"});
										}

									}

								}
								else if (!$this.hasClass('list_bg')) {//有未读消息,且不为当前聊天对象,则置顶,但滚动条维持原状
									if (j != 0) {
										if (newinfoflag) {
											var tempobj = $this.clone(true);
											$this.remove();
											$imlistul.prepend(tempobj);

										}

									}
								}
							}

                    }
                    else{
                        if(chatlistliid==id){
                            if($this.hasClass('list_bg') && j!=0){ //从$.i18n.prop('cdf76a200cf059d13e9123796c6b36a0')过来的,要把当前对象置顶
                                var $tempchatwin= $('#IM-Chatwin');
                                if($tempchatwin.attr('chatlinkbtn')){
                                    var tempindex=$this.index();
                                    var top=tempindex*56;
                                    //置顶(仅前端,没有存到数据库)
                                    // var tempobj=$this.clone(true);
                                    // $this.remove();
                                    // $imlistul.prepend(tempobj);
                                     $tempchatwin.removeAttr('chatlinkbtn');
                                    //以下是设置滚动条

										$('#im_ul_wrapper.mCustomScrollbar').mCustomScrollbar('scrollTo', (top + "px"), {scrollInertia: -10});
										otherpagesflag = true;

										$.cookie("ulscrolltop", ('-' + top + 'px'), {"expires": 1, path: "/"});


									}
								}
								else if ($this.hasClass('list_bg') && j == 0) {

									//$('#im_ul_wrapper.mCustomScrollbar').mCustomScrollbar('scrollTo',"top" ,{scrollInertia:-10});
								}
							}

							circle++;
						}


					}

					if (!ifhasdom) {//如果这一条数据并没有在原来的会话列表中,则prepend到最前面(一般是有新消息时才会出现新对象)

						var src = '';
						if (chatList[i].headUrl == '') {
							src = '/images/user_pic-225x225.png';
						} else {
							src = _this.opts.picture_host + '/get.php?pn=' + chatList[i].headUrl + '&pt=0&st=small';
						}

						var readno = (parseInt(chatList[i].readNo) > 99) ? 99 : chatList[i].readNo;


						var nickName2 = chatList[i].nickName;
						str += '<li id="plug-chat-' + chatList[i].houseId + '-' + chatList[i].userId_to_id + '" lihouseid="' + chatList[i].houseId + '" userto="' + chatList[i].userId_to_id + '" style="" class=""><div class="lichild">'
							+ '<span class="im_list_img"><img class="IM-UserHeadImg" width="30" height="30" src="' + src + '"></span>'
							+ '<span class="im_list_name IM-UserName" title="' + chatList[i].nickName + '">' + nickName2 + '</span>'
							+ '<a class="close ' + chatList[i].readYN + '" href="javascript:void(0);"><span>' + readno + '</span></a><span class="deleteicon" style="display:none;"><img src="/images/deleteicon2.png"/></span> </div></li>';
					}

				}


				if (chatList.length) {
					if (circle != chatList.length * len)//如果新列表中一条未读消息也没有,则不删除
						$imlistul.find('li').not('[curexitflag=true]').remove();//把新会话列表中没有的给删掉
					$imlistul.find('li').removeAttr('curexitflag');

				}
				else {//别的端把聊天列表全删了,则关闭聊天框

					// $('.im_L.im_M.IM-BtnMouse-Msg').hide();
					// $('#webim-dom').hide();
					return;

				}

				if (str) {//把原来会话列表里面没有的dom元素加到文档中
					$imlistul.prepend(str);
				}
			}
			else {//页面刚加载,还没有数据

				var listr = '';
				for (var i = 0; i < chatList.length; i++) {
					if (tag) {
						if ((temporary_house_user_to == chatList[i].houseId + '-' + chatList[i].userId_to_id) || (temporary_house_user_to.split('-')[1] == chatList[i].userId_to_id)) {
							deleteAlready = false;
						}
					}
					var src = '';
					if (chatList[i].headUrl == '') {
						src = '/images/user_pic-225x225.png';
					} else {
						src = _this.opts.picture_host + '/get.php?pn=' + chatList[i].headUrl + '&pt=0&st=small';
					}
					try {
						// var nickName2 = chatList[i].nickName.length>4?(chatList[i].nickName.substring(0, 4)+'..'):chatList[i].nickName;
						var nickName2 = chatList[i].nickName;
						var readno = (parseInt(chatList[i].readNo) > 99) ? 99 : chatList[i].readNo;


						listr += '<li id="plug-chat-' + chatList[i].houseId + '-' + chatList[i].userId_to_id + '" lihouseid="' + chatList[i].houseId + '" userto="' + chatList[i].userId_to_id + '" style="" class=""><div class="lichild">'
							+ '<span class="im_list_img"><img class="IM-UserHeadImg" width="30" height="30" src="' + src + '"></span>'
							+ '<span class="im_list_name IM-UserName" title="' + chatList[i].nickName + '">' + nickName2 + '</span>'
							+ '<a class="close ' + chatList[i].readYN + '" href="javascript:void(0);"><span>' + readno + '</span></a><span class="deleteicon" style="display:none;"><img src="/images/deleteicon2.png"/></span> </div></li>';

					} catch (e) {

					}
				}

				if (listr) {
					$('.im_list_ul').append(listr);
					// $('.im_L.im_new_L.im_new_M.im_new_hover').addClass('open');

				}

				else {//别的端把聊天列表全删了,则关闭聊天框
					// if($('.im_L.im_M.im_new_L.im_new_M.im_new_hover').hasClass('open')) {
					//     $('#IM-Chatwin').hide();
					//     $('#messlist-box').show();
					//     $('.look-notify-items-box').hide();
					//     $('.look-collect-box').hide();
					//     $('.look-feedback-box').hide();
					//     $('.im_L.im_new_L.im_new_hover').removeClass('open');
					//     $('.im_L.im_new_L.im_new_M.im_new_hover').addClass('open');
					// } else {
					//     $('#messlist-box').hide();
					// }
					// $('#IM-Chatwin').hide();
					// $('#messlist-box').show();
					// $('.im_L.im_M.IM-BtnMouse-Msg').hide();

					// $('.im_L.im_new_L.im_new_hover').removeClass('open');
					jQuery.cookie("im_news_overflow", '', {"expires": 1000, path: "/"});
					/*改聊天按钮闪动bug*/
					// $('#webim-dom').hide();
					return;
				}


			}


			// console.log('tag:'+tag+' deleteAlready:'+deleteAlready);

			if (tag && deleteAlready) {
				jQuery.cookie("chatwin_house_user_to", house_user_to, {path: "/"});
			} else if (tag && !deleteAlready) {
				house_user_to = temporary_house_user_to;
			}

			if (len > 0) {

				// var $listbg=$('.im_list_ul').find('.list_bg');
				// if($listbg.length>0){
				//
				//
				//     var id=$listbg.attr('id');
				//     if(id){
				//         var con=id.split('plug-chat-')[1];

				var house_user_to = $.cookie('chatwin_house_user_to');//当前聊天对象
				con = house_user_to.split('-');
				var houseId = con[0];
				var userId_to = con[1];

				var $plug_chat = $('#plug-chat-' + house_user_to);
				$plug_chat.addClass('list_bg').siblings().removeClass('list_bg');
				$plug_chat.children('.close').removeClass('unreadCount');
				$plug_chat.children('.close').children('span').html('');


				//给控制台设置当前对话条件
				$('.im_list_ul').attr('data-control', houseId + '-' + userId_to);
				var chatwin_overflow = jQuery.cookie("chatwin_overflow");
				if (chatwin_overflow == 'show') {
					_this.setFirstMessAndHouse(houseId, userId_to);
				}

				if (data.result.OneSession && data.result.OneSession[0]) {
					_this.displayChatInfo(data.result.OneSession, houseId, userId_to, false);
				}


				// }


				// }

			}
			else {//新加载,则设置第一个为当前聊天对象

				//返回当前第一个用户的houseId和userId
				var cona = house_user_to.split("-");
				var houseId = cona[0];
				var userId_to = cona[1];

				var $plug_chat = $('#plug-chat-' + house_user_to);
				$plug_chat.addClass('list_bg');
				$plug_chat.children('.close').removeClass('unreadCount');
				$plug_chat.children('.close').children('span').html('');


				//聊天人员列表的滚动条设置 
				var $listbg = $('.im_list_ul').find('.list_bg');
				if ($listbg.length > 0) {
					var newindex = $listbg.index();
					if (newindex) {
						$('#im_ul_wrapper').attr('firstuser', '1').attr('talktop', newindex * 40).mCustomScrollbar("scrollTo", (newindex * 40 + "px"), {scrollInertia: 10});
						otherpagesflag = true;
						$.cookie("ulscrolltop", ('-' + (newindex * 40) + 'px'), {"expires": 1, path: "/"});

					}
				}


				//把当前聊天对象的未读信息设置为已读
				if ($('#IM-Chatwin').css('display') == 'block') {
					if (userId_to)
						_this.notifyOneSessionHasReadToServer(userId_to);//把当前会话对象的消息设置为已读

				}


				// //给控制台设置当前对话条件
				// $('.im_list_ul').attr('data-control',houseId+'-'+userId_to);
				// var chatwin_overflow=jQuery.cookie("chatwin_overflow");
				// if(chatwin_overflow =='show'){
				//     _this.setFirstMessAndHouse(houseId,userId_to);
				// }
				//
				if (data.result.OneSession && data.result.OneSession[0])
					_this.displayChatInfo(data.result.OneSession, houseId, userId_to, false);


			}


			var newindex = $imlistul.find('.list_bg').index();
			var alllistlen = $imlistul.find('li').length;


			//以下要设置滚动条 如果当前会话被挤到下面

			/**
			 * 代码
			 */
				//可显示8条数据,每条数据的高度是56px


			var $imchatwintemp = $('#IM-Chatwin');
			if ($imchatwintemp.attr('setscrolltopflag') == 1) {

				$imchatwintemp.removeAttr('setscrolltopflag');//只在打开窗口、点击联系房东、切换时重设scrolltop,不再每次轮询都刷新


				if (alllistlen >= 8) {
					if (newindex != oldindex) {


						var im_list_ulscrolltop = $.cookie("im_list_ulscrolltop");
						if (im_list_ulscrolltop) {
							$('.imtalk_list .mCustomScrollBox .mCSB_container').css('top', im_list_ulscrolltop);

							$('#chatcontentlistbox #scrollbar-msg-content-' + houseId + '-' + userId_to).mCustomScrollbar('scrollTo', "bottom", {scrollInertia: -4});

							return;
						}


						var top = $('.imtalk_list .mCustomScrollBox .mCSB_container').css('top');
						if (top) {
							top = top.replace(/[^0-9]/ig, "");
						}
						var visiblestartindex = parseInt(top / 56);
						if (newindex > (visiblestartindex + 1) && newindex < (visiblestartindex + 8)) {
							//原本就在可视区内,不用改
						}
						else if (newindex < (visiblestartindex + 1)) {//应该往上滚
							var cert = visiblestartindex - newindex;
							var len = top - cert * 56;
							if (len < 0) {
								$('.imtalk_list .mCustomScrollBox .mCSB_container').mCustomScrollbar({
									setTop: '0px',
									scrollInertia: '-10'
								});
							}
							else {

								$('.imtalk_list .mCustomScrollBox .mCSB_container').mCustomScrollbar({
									setTop: ('-' + len + 'px'),
									scrollInertia: '-10'
								});

							}

							// $('.imtalk_list .mCustomScrollBox .mCSB_container').css('top','-'+len+'px');
						}
						else if (newindex > (visiblestartindex + 8)) {//往下滚

							var cert = newindex - visiblestartindex - 7;
							var len = cert * 56 + top;
							var allheight = (alllistlen - 8) * 56;
							if (len >= allheight) {
								$('.imtalk_list .mCustomScrollBox .mCSB_container').css('top', '-' + allheight + 'px');
							}
							else {

								$('.imtalk_list .mCustomScrollBox .mCSB_container').css('top', '-' + len + 'px');
							}
						}

					}
					else {
						if (!otherpagesflag) {
							var ulscrolltop = $.cookie("ulscrolltop");

							var $ulimtalklistmsb = $('.imtalk_list .mCustomScrollBox .mCSB_container');
							var oldtop = $ulimtalklistmsb.css('top');


							var im_list_ulscrolltop = $.cookie("im_list_ulscrolltop");

							if (ulscrolltop) {


								if (ulscrolltop != oldtop) {
									$ulimtalklistmsb.css('top', ulscrolltop);

									var $msgcontent = $('#chatcontentlistbox .msg-content:visible');
									if ($msgcontent.length > 0)
										$msgcontent.find('.mCustomScrollbar').mCustomScrollbar('scrollTo', "bottom", {scrollInertia: -400});
								}
								else if (ulscrolltop != im_list_ulscrolltop) {

									$ulimtalklistmsb.css('top', im_list_ulscrolltop);
									var $msgcontent = $('#chatcontentlistbox .msg-content:visible');
									if ($msgcontent.length > 0)
										$msgcontent.find('.mCustomScrollbar').mCustomScrollbar('scrollTo', "bottom", {scrollInertia: -400});

								}
							}


						}


					}

				}
				else {
					$('.imtalk_list .mCustomScrollBox .mCSB_container').css('top', '0px');
				}

			}


		},

		/*
     * 设置刚打开窗口的时候的聊天信息展示
     */
		setFirstMessAndHouse: function (houseId, userId_to) {
			var _this = this;
			//获取房源信息


			// if($('#msg-content-'+houseId+'-'+userId_to).length > 0){
			//     $('.msg-content').hide();
			//     $('#msg-content-'+houseId+'-'+userId_to).show();
			// }else{
			//     if(houseId &&userId_to){
			//         console.log('每次触发');
			//         _this.fetchOldMessage(houseId,userId_to);
			//     }
			// }
			// )

			var $msgcontent = $('#IM-Content .msg-content[msgusertag="' + userId_to + '"]');
			if ($msgcontent.length > 0) {
				$('.msg-content').hide();
				$msgcontent.show();
			}
			else {
				if (houseId && userId_to) {
					//console.log('每次触发');
					_this.fetchOldMessage(houseId, userId_to);
				}
			}


			/*这里进行循环查询*/
			//如果是重新打开的页面就
			var href = window.location.href;
			if (jQuery.cookie("chatwin_prev_house_user_to") != href + houseId + '-' + userId_to) {
				jQuery.cookie("chatwin_prev_house_user_to", href + houseId + '-' + userId_to, {path: "/"});
			}
			//开启循环查询等待
			// _this.checkChatInfo('on',houseId,userId_to);
			//获取房源信息

			var $plugcurlu = $('#IM-LodgeUnitShow .plug-curlu[useridto="' + userId_to + '"]');


			if ($plugcurlu.length > 0) {
				$('.plug-curlu').hide();
				$plugcurlu.show();
			} else {
				_this.getHouseInfo(houseId, userId_to);
			}

			// if($('#plug-curlu-'+houseId+'-'+userId_to).length > 0){
			//     $('.plug-curlu').hide();
			//     $('#plug-curlu-'+houseId+'-'+userId_to).show();
			// }else{
			//     _this.getHouseInfo(houseId,userId_to);
			// }
		},

		/*
     * 点击联系房东的时候弹出聊天对话框
     */
		newChatForMe: function () {

			var _this = this;
			$('body').on('click', '#detailpageBtn .contact-owner,#myjourneywebbtn .contact-owner,#journeyorderpagebtn .lianxiwomen,#landlordorderbtn .lianxiwomen,.reservations .contact-custorm', function () {

				$('#messlist-box').hide();
				jQuery.cookie("hasMessageList", 'true', {"expires": 1, path: "/"});   // 新加
				// jQuery.cookie("openChatBoxMessageList",'true',{"expires":1,path:"/"});
				$('#IM-Chatwin').attr('setscrolltopflag', '1');//左侧聊天列表是否设置重设scrolltop

            var startdatechat = $.cookie(window.location.pathname+"startdatechat")
            var enddatechat = $.cookie(window.location.pathname+"enddatechat")

				store.remove('houseMessageListSwitch');

				$('.warnclan').hide();
				$.cookie("openedchatbox", '1', {"expires": 1, path: "/"});
				$.cookie("im_list_ulscrolltop", null, {"expires": -1, path: "/"});
				var $this = $(this);
				if ($this.hasClass('showconsumbox') && (startdatechat == null)) {//房源详情页面的联系房东,要显示咨询框
					//
					$('.im_clanbox').show();
					$('.im_operater').hide();

                var $chanselectbox=$('#chan_definegroup .defineselectbox');
                var peonum=$this.attr('data-peo-num');
                var strli='';
                if(peonum){
                    for(var i=0;i<peonum;i++){
                        strli+='<li value='+(i+1)+'>'+(i+1)+$.i18n.prop('4bf8668ff124218a71b6c3de6c83e300') + '</li>';
                    }

                }
                else{
                    strli+= '<li value="1">' + $.i18n.prop('a88ba0f121ccd0ca98a30293fb26fac6') + '</li>';
                }
                var selecttop=peonum*23+2;

					$chanselectbox.css('top', '-' + selecttop + 'px').html('').append(strli);


				}
				else {
					$('.im_operater').show();
					$('.im_clanbox').hide();
				}

				$('.im_L.im_M').addClass('open');

				var houseId = $this.attr('data-houseId');
				var userId_to = $this.attr('data-userId');
				if (!houseId || !userId_to)
					return;

				var $imchatwin = $("#IM-Chatwin");


				//如果聊天列表里原本就有这个房东的消息,且不是同一个房源,则修改这一条聊天对象的houseid
				var $samelorder = $imchatwin.find('.im_ul_wrapper .im_list_ul li[userto="' + userId_to + '"]');

				if ($samelorder.length > 0) {
					//console.log('已存在此聊天对象');
					var samelorder_id = $samelorder.attr('id');
					var samehouserIduserId = samelorder_id.split('plug-chat-')[1];

					var $chatcontent = $('#chatcontentlistbox #msg-content-' + samehouserIduserId);

					var samelorder_houserId = samehouserIduserId.split('-')[0];

					if (samelorder_houserId != houseId) {//说明点击的是同一个房东的不同房源
						$samelorder.attr('id', 'plug-chat-' + houseId + '-' + userId_to);

						if ($chatcontent.length > 0) {//右边的聊天内容栏也要改

							$chatcontent.attr('id', 'msg-content-' + houseId + '-' + userId_to);
							$chatcontent.find('.im_user_infor').attr('id', 'info-msg-content-' + houseId + '-' + userId_to);
							$chatcontent.find('.talk_con').attr('id', 'scrollbar-msg-content-' + houseId + '-' + userId_to);
						}

						_this.getHouseInfo(houseId, userId_to);//最右侧的房源信息也要改

					}


				}
				else {
					var $houserbox = $('#IM-CurLodgeUnit').find('#plug-curlu-' + houseId + '-' + userId_to);
					if ($houserbox.length == 0) {
						_this.getHouseInfo(houseId, userId_to);//直接加载房源信息,防止速度过慢
					}

				}


				if (jQuery.cookie("yyoh") && jQuery.cookie("id")) {
					if (userId_to != jQuery.cookie("id")) {

						jQuery.cookie("chatwin_userId_to", userId_to, {"expires": 1000, path: "/"});

						//让底部的消息中心显示
						jQuery.cookie("im_news_overflow", jQuery.cookie("id") + '-show', {"expires": 1000, path: "/"});

						$(".im_news .im_L.im_M,.im_news .bg_img_fff_b").show();
						$imchatwin.attr('chatlinkbtn', 1);
						//让对话框显示
						if ($imchatwin.css("display") == 'none') {
							//如果是空的话就隐藏
							jQuery.cookie("chatwin_overflow", 'show', {"expires": 1000, path: "/"});
							//打开聊天框
							if (jQuery.cookie("chatwin_positioning")) {
								var position = jQuery.cookie("chatwin_positioning");
								var cona = position.split("-");
								var chat_x = cona[0];
								var chat_y = cona[1];
								$imchatwin.css({top: chat_x, left: chat_y, display: 'block'});

							}
							else {
								var height = $(window).height();
								var width = $(window).width();
								$imchatwin.css({top: (height - 500) / 2 + 'px', left: (width - 788) / 2 + 'px'});
							}


							//暂时注释掉


							var $msgcontent = $('#chatcontentlistbox .msg-content:visible');
							if ($msgcontent.length > 0)
								$msgcontent.find('.mCustomScrollbar').mCustomScrollbar('scrollTo', "bottom", {scrollInertia: -400});

						}

						//将当前会话窗口保存到cookie中
						jQuery.cookie("chatwin_house_user_to", houseId + '-' + userId_to, {path: "/"});
						//给外层控制台设置当前要获取的聊天对话
						$('.im_list_ul').attr('data-control', houseId + '-' + userId_to);
						//将当前消息放入cookie中以便能够保存足够长的时间
						var img = $this.attr('data-url');
						var name = $this.attr('data-nickName');


						var nowDate = new Date();
						var nowTime = nowDate.getFullYear() + '-' + ((nowDate.getMonth() > 8) ? nowDate.getMonth() + 1 : ('0' + (nowDate.getMonth() + 1))) + '-' + ((nowDate.getDate() > 9) ? nowDate.getDate() : ('0' + nowDate.getDate())) + ' ' + ((nowDate.getHours() > 9) ? nowDate.getHours() : ('0' + nowDate.getHours())) + ':' + ((nowDate.getMinutes() > 9) ? nowDate.getMinutes() : ('0' + nowDate.getMinutes())) + ":" + ((nowDate.getSeconds() > 9) ? nowDate.getSeconds() : ('0' + nowDate.getSeconds()));
						var expireDate = nowDate.getTime() + 1000 * 60 * 60 * 24 * 7;
						var chat = {
							"nickName": name,
							"userId_to_id": userId_to,
							"userId": jQuery.cookie("id"),
							"houseId": houseId,
							"headUrl": img,
							"readYN": '',
							"readNo": '',
							"publish_time": nowTime,
							"survival": expireDate
						};
						var temporary = '';
						var nowIm = [];
						if (jQuery.cookie("temporary_chat")) {
							var old_chat = jQuery.cookie("temporary_chat");
							var existIm = JSON.parse(old_chat);
							var tag = true;
							for (var i = 0; i < existIm.length; i++) {
								if (existIm[i].userId_to_id == userId_to && existIm[i].userId == jQuery.cookie("id") && existIm[i].houseId == houseId) {
									nowIm.push(chat);
									tag = false;
								} else {
									nowIm.push(existIm[i]);
								}
							}
							if (tag) {
								nowIm.push(chat);
							}
						} else {
							nowIm.push(chat);
						}
						temporary = JSON.stringify(nowIm);
						jQuery.cookie("temporary_chat", temporary, {"expires": 1, path: "/"});
						//重新进行外部循环搜索（关掉当前循环，直接进行搜索，然后再次打开循环搜索）

						// var $im_ul_wrapper=$('#im_ul_wrapper');
						// var currentTop=$im_ul_wrapper.attr('data-scroll-top');
						// if(currentTop)
						//     $im_ul_wrapper.find('.mCustomScrollBox').children('.mCSB_container').css('top',currentTop);


						//_this.getMessageList('',houseId,userId_to);


						_this.checkMessageList(houseId, userId_to);

                    window.clearInterval(_this.opts.chatUserList);
                    window.clearInterval(_this.opts.chatUserList_wait);
                    _this.opts.chatUserList = window.setInterval(function(){_this.checkMessageList(houseId,userId_to)},5000);
                }else{
                    alert($.i18n.prop('6f629bc9b6b6ad8ce0f356f0c0c42184'));
                }
            }else{
                var history = window.location.pathname+window.location.search;
                history = history.length?('?history='+history):'';
                window.location.href="/login/p_login"+history;
            }
            return false;

			})


		},


		/*
      * 设定窗口进入的时候显示或者隐藏还有所在位置
      */
		setOverflowAndPosition: function () {
			var _this = this;
			//登陆状态下才能够进行下一步
			if (jQuery.cookie("yyoh") && jQuery.cookie("id")) {
				//如果消息框状态为显示，才将消息进行展示出来
				if (jQuery.cookie("im_news_overflow") && jQuery.cookie("im_news_overflow") == (jQuery.cookie("id") + '-show')) {
					$(".im_news .im_L.im_M,.im_news .bg_img_fff_b").show();


					if (!jQuery.cookie("chatwin_overflow") || jQuery.cookie("chatwin_overflow") == 'hidden') {
						//如果是空的话就隐藏
						jQuery.cookie("chatwin_overflow", 'hidden', {path: "/"});


						$("#IM-Chatwin,.recommend-house").hide();

						$('.im_L.im_M').removeClass('open');
					} else {
						if (jQuery.cookie("chatwin_positioning")) {
							var position = jQuery.cookie("chatwin_positioning");
							var cona = position.split("_");
							var chat_x = cona[0];
							var chat_y = cona[1];
							$("#IM-Chatwin").css({top: chat_y + 'px', left: chat_x + 'px'});
						}
						else {
							var height = $(window).height();
							var width = $(window).width();
							// $("#IM-Chatwin").css({ top: (height-500)/2+'px', left: (width-788)/2+'px'});
							$("#IM-Chatwin").css({bottom: '68px', right: '340px'});
						}

						$("#IM-Chatwin").show();

						$('.im_L.im_M').addClass('open');
					}
				}
			}
		},

		/*
     * 根据房源ID和用户ID，获取房源信息
     */
     getHouseInfo:function(houseId,userId_to){
        var typeNum = '1';
        if($.cookie("buyer_currency")){
            typeNum = $.cookie("buyer_currency");
        }
        var currency_symbol = '￥';
        if($.cookie("currency_symbol")){
            currency_symbol = $.cookie("currency_symbol");
        }
        if(houseId==0){
           $('#IM-LodgeUnitShow .nohousebox').show();
            $('#IM-LodgeUnitShow .plug-curlu').hide();
            return;
        }
        else{
            $('#IM-LodgeUnitShow .nohousebox').hide();
            $('#IM-LodgeUnitShow .plug-curlu').show();
        }
        $('.buyer_currency_symbol').html(currency_symbol);
        var value = '{"houseId":"'+houseId+'","isCurrency":"1","typeNum":"'+typeNum+'","attrList":["*"],"cut":{"height":"560","width":"840"}}';
        var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('725e31c79d38f311525f82bdaae8960e'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
        var myDate = new Date();
        treatData('house/getHouseInfoForIM',value,function(data){
            if(data.status.status_code == 0){
                //console.log('调用gethouseinfo');
                $('.plug-curlu').hide();
                var price = data.result.houseInfo.pricePerNight;
                try{
                    if(data.result.houseInfo.houseCalendarPrice){
                        price = data.result.houseInfo.houseCalendarPrice;
                    }
                }catch (e){}


                var name4=(data.result.houseInfo.levelName4&&(data.result.houseInfo.levelName4!=$.i18n.prop('f5a7f30e1878cd0b13bde467d4f8d713')))?('-<span class="IM-CurLuRenttype">'+data.result.houseInfo.levelName4+'</span>'):'';
                var str = '<div class="plug-curlu" houseid="'+houseId+'" useridto="'+userId_to+'" id="plug-curlu-'+houseId+'-'+userId_to+'" style=""><div class="im_room_tabsbox noselect">\n\
                            <ul class="im_room_tabs" id="tag-plug-curlu-'+houseId+'-'+userId_to+'" style="display: block;"><li class="tab_no">'+$.i18n.prop('a4225398920e8b34356200d5da7c8d95')+'</li></ul></div>\n\
                            <div class="cur_room_info">\n\
                                <a href="/h/' + houseId + '" target="_blanlk" class="IM-CurLodgeUrl">\n\
                                    <img width="210" class="IM-CurLuHeadImg" src="' + data.result.pictureList[0].url + '">\n\
                                </a>\n\
                                <p class="bor_P">'+currency_symbol+'<span class="fontsize20">'+Math.round(price)+'</span>/'+$.i18n.prop('2a668c21c6700e683773fa28c9ab4b3c')+'</p>\n\
                                <p class="bor_second"><a href="/h/'+houseId+'" class="IM-CurLodgeUnitName IM-CurLodgeUrl">'+data.result.houseInfo.title+'</a></p>\n\
                                <p class="bor_T">\n\
                                    <span class="IM-CurLodgeUnitAddr">'+roomType[data.result.houseInfo.roomType]+'</span>-<span class="IM-CurLodgeType">' + $.i18n.prop('a8fe7295d7131b9ff864e9134a7a8027')+data.result.houseInfo.accommodateNum+$.i18n.prop('5aa37d5fd72555446e3d73c9fd0a52b8') +'</span>-<span class="IM-CurLuRenttype">'+data.result.houseInfo.commentCount+$.i18n.prop('521221622c87df4d119042eb96159399')+'</span>\n\
                                </p>\n\
                                <p class="bor_last">\n\
                                    <span class="IM-CurLodgeUnitAddr">' + data.result.houseInfo.levelName1 + '</span>-<span class="IM-CurLodgeType">' + data.result.houseInfo.levelName2 + '</span>' + '<span>' + name4 + '</span>\n\
                                </p>\n\
                            </div>\n\
                            <div class="cur_room_info2"></div>\n\
                        </div>';


					var $oldplug = $('#IM-CurLodgeUnit').find('.plug-curlu[useridto="' + userId_to + '"]').remove();
					// console.log('删除的userId_to:'+userId_to);
					$('#IM-CurLodgeUnit').append(str);


				}


			});
		},

		/*
     * 页面进入获取历史聊天信息
     */
		fetchOldMessage: function (houseId, userId_to, sortflag) {
			var _this = this;
			var param = {};
			param.yyoh = jQuery.cookie("yyoh");
			// param.userId_from = jQuery.cookie("id");
			param.userId = jQuery.cookie("id");
			param.houseId = houseId;
			// param.lastSendTime = '9999-99-99 00:00:00';
			param.userId_to_id = userId_to;
			param.isTestApi = '';//标明不是数据桩
			var msgId = 0;

			var $list_bg = $('.im_list_ul .list_bg');

			if ($list_bg.length > 0) {
				var id = $list_bg.attr('id');
				id = id.split('plug-chat-')[1];
				var $curmsgcontent = $('.msg-content[id=msg-content-' + id + ']');
				if ($curmsgcontent.length > 0) {
					$curlastli = $curmsgcontent.find('.mCSB_container').find('.talk_time:eq(0)');
					if ($curlastli.length > 0) {
						msgId = $curlastli.attr('id');
					}

				}

			}


			param.msgId = msgId;


			// var range = {};
			// range.page = 0;
			// range.pageSize = 200;
			// param.range = range;


			var value = JSON.stringify(param);
			treatData('pushMessage/getHistoryMessageList', value, function (data, url) {
				if (data.status.status_code == 0) {

					_this.displayChatInfo(data.result.MessageList, houseId, userId_to, sortflag);
				}
			});
		},
		/****
		 * 展示聊天信息 新增
		 * sortflag 为true时加载历史,为false时加载新消息
		 */

		displayChatInfo: function (data, houseId, userId_to, sortflag) {
			try {
				var _this = this;

				// console.log('传地来的usderid,houseid: houseId:'+houseId+' userId_to:'+userId_to);
				var tag = 'content-' + houseId + '-' + userId_to;
				var data_MessageList = data;

				var str = '';

				var $contentbox = $('#chatcontentlistbox').find('[msgusertag="' + userId_to + '"]');
				var linkdusertoid = '';

				var hasimgflag = 0;


				if (data && data.length) {
					for (var i = data_MessageList.length - 1; i >= 0; i--) {


						var chatContent = '';
						var message = '';
						try {
							message = JSON.parse(data_MessageList[i].message);
						} catch (e) {
							break;
						}

						if (message) {
							chatContent = message.chatContent;
							if (chatContent) {
								chatContent = chatContent.replace(new RegExp("<", "g"), "&lt;");
								chatContent = chatContent.replace(new RegExp(">", "g"), "&gt;");
							}

						}

						//if(data.result.MessageList[i].messageType == '0'){

						//var param_userId=jQuery.cookie("id");
						var param_userId = userId_to;
						if (chatContent) {

                             if(data_MessageList[i].messageType == '-2'){//有敏感词
                                 chatContent=chatContent.split($.i18n.prop('8f54f448ca6bb2f190652dbc95b0225a'))[0];
                             }


							if ($contentbox.length > 0) {

								if ($contentbox.find('#' + data_MessageList[i].id).length <= 0) {

									if (data_MessageList[i].userId_to == param_userId) {//是当前用户发给别人的

										if (data_MessageList[i].messageType == '2') {
											str = str + '<p class="talk_time" displayChatInfoaaaa chat id="' + data_MessageList[i].id + '" style="display: block;">' + data_MessageList[i].publish_time.substring(5, 19) + '</p>\n\
                                                <div class="box red_bg message_pic" id="' + data_MessageList[i].msgKey + '">\n\
                                                    <div><img class="pic" src=' + chatContent + '?pt=1&st=large /></div>\n\
                                                    <span></span>\n\
                                                </div>';

                                             hasimgflag++;
                                         }else if(message.recommendHouseId){
                                             var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                             var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                             var currency_symbol = currency_symbol_arr[message.recommendHouseCurrency-1].symbol || '';
                                             str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                                 '<div class="box white_bg" id="'+data_MessageList[i].msgKey+'">' +
                                                 '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                                 '<img src="'+message.recommendHousePicture+'"/>' +
                                                 '<div class="houseInfo">' +
                                                 '<p>'+message.recommendHouseTitle+'</p>' +
                                                 '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') + '</p>' +
                                                 '<p>'+currency_symbol+Math.round(message.recommendHousePrice)+'</p>' +
                                                 '</div>' +
                                                 '</a>' +
                                                 '<span></span>' +
                                                 '</div>'
                                         }else{

											//console.log('displayChatInbbbb:'+'param_userId:'+param_userId+'data_MessageList[i].userId_from:'+data_MessageList[i].userId_from);

											str = str + '<p class="talk_time" displayChatInfobbbb id="' + data_MessageList[i].id + '" style="display: block;">' + data_MessageList[i].publish_time.substring(5, 19) + '</p>\n\
                                                <div class="box red_bg" id="' + data_MessageList[i].msgKey + '">\n\
                                                    <div>' + chatContent + '</div>\n\
                                                    <span></span>\n\
                                                </div>';
										}

                                         if(data_MessageList[i].messageType == '-2'){
                                             str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                         }
                                     }
                                     else if(data_MessageList[i].userId_from== param_userId){ //是别的聊天对象发给当前用户的

										if (data_MessageList[i].messageType == '2') {
											str = str + '<p class="talk_time" displayChatInfocccc id="' + data_MessageList[i].id + '" style="display: block;">' + data_MessageList[i].publish_time.substring(5, 19) + '</p>\n\
                                            <div class="box message_pic" id="' + data_MessageList[i].msgKey + '">\n\
                                                <div><img class="pic" src=' + chatContent + '?pt=1&st=large /></div>\n\
                                                <span></span>\n\
                                            </div>';

                                             hasimgflag++;
                                         }else if(message.recommendHouseId){
                                             var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                             var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                             var currency_symbol = currency_symbol_arr[message.userCurrency-1].symbol || '';
                                             str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                                 '<div class="box white_bg pos_left" id="'+data_MessageList[i].msgKey+'">' +
                                                 '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                                 '<img src="'+message.recommendHousePicture+'"/>' +
                                                 '<div class="houseInfo">' +
                                                 '<p>'+message.recommendHouseTitle+'</p>' +
                                                 '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') + '</p>' +
                                                 '<p>'+currency_symbol+Math.round(message.userPrice)+'</p>' +
                                                 '</div>' +
                                                 '</a>' +
                                                 '<span></span>' +
                                                 '</div>'
                                         }else{
                                             str = str + '<p class="talk_time" displayChatInfodddd id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>\n\
                                            <div class="box" id="'+data_MessageList[i].msgKey+'">\n\
                                                <div>'+chatContent+'</div>\n\
                                                <span></span>\n\
                                            </div>';
										}


                                         if(data_MessageList[i].messageType == '-2'){
                                             str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                         }
                                     }

								}
							}
							else {


								if (data_MessageList[i].userId_to == param_userId) {

									if (data_MessageList[i].messageType == '2') {
										str = str + '<p class="talk_time" displayChatInff id="' + data_MessageList[i].id + '" style="display: block;">' + data_MessageList[i].publish_time.substring(5, 19) + '</p>\n\
                                            <div class="box red_bg message_pic" id="' + data_MessageList[i].msgKey + '">\n\
                                                <div><img class="pic" src=' + chatContent + '?pt=1&st=large /></div>\n\
                                                <span></span>\n\
                                            </div>';

                                         hasimgflag++;
                                     }else if(message.recommendHouseId){
                                         var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                         var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                         var currency_symbol = currency_symbol_arr[message.recommendHouseCurrency-1].symbol || '';
                                         str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                             '<div class="box white_bg" id="'+data_MessageList[i].msgKey+'">' +
                                             '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                             '<img src="'+message.recommendHousePicture+'"/>' +
                                             '<div class="houseInfo">' +
                                             '<p>'+message.recommendHouseTitle+'</p>' +
                                             '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') + '</p>' +
                                             '<p>'+currency_symbol+Math.round(message.recommendHousePrice)+'</p>' +
                                             '</div>' +
                                             '</a>' +
                                             '<span></span>' +
                                             '</div>'
                                     }else{
                                         //console.log('displayChatInfg:'+'param_userId:'+param_userId+'data_MessageList[i].userId_from:'+data_MessageList[i].userId_from);
                                         str = str + '<p class="talk_time" displayChatInfg id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>\n\
                                            <div class="box red_bg" id="'+data_MessageList[i].msgKey+'">\n\
                                                <div>'+chatContent+'</div>\n\
                                                <span></span>\n\
                                            </div>';
									}

                                     if(data_MessageList[i].messageType == '-2'){
                                         str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                     }
                                 }
                                 else if(data_MessageList[i].userId_from== param_userId){
                                     if(data_MessageList[i].messageType == '2'){
                                         str = str + '<p class="talk_time" displayChatInh id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>\n\
                                        <div class="box message_pic" id="'+data_MessageList[i].msgKey+'">\n\
                                            <div><img class="pic" src='+chatContent+'?pt=1&st=large /></div>\n\
                                            <span></span>\n\
                                        </div>';

                                         hasimgflag++;
                                     }else if(message.recommendHouseId){
                                         var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                                         var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                                         var currency_symbol = currency_symbol_arr[message.userCurrency-1].symbol || '';
                                         str += '<p class="talk_time" displayChatInff id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>' +
                                             '<div class="box white_bg pos_left" id="'+data_MessageList[i].msgKey+'">' +
                                             '<a href="/h/'+message.recommendHouseId+'" target="_blank">' +
                                             '<img src="'+message.recommendHousePicture+'"/>' +
                                             '<div class="houseInfo">' +
                                             '<p>'+message.recommendHouseTitle+'</p>' +
                                             '<p>'+roomType[message.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+message.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') +'</p>' +
                                             '<p>'+currency_symbol+Math.round(message.userPrice)+'</p>' +
                                             '</div>' +
                                             '</a>' +
                                             '<span></span>' +
                                             '</div>'
                                     }else{
                                         str = str + '<p class="talk_time" displayChatIni id="'+data_MessageList[i].id+'" style="display: block;">'+data_MessageList[i].publish_time.substring(5,19)+'</p>\n\
                                        <div class="box" id="'+data_MessageList[i].msgKey+'">\n\
                                            <div>'+chatContent+'</div>\n\
                                            <span></span>\n\
                                        </div>';
									}


                                     if(data_MessageList[i].messageType == '-2'){
                                         str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                                     }
                                 }
                             }
                         }


					}
				}


				if ($contentbox.length > 0) {// 该聊天对象对应的msg-content已存在
					if (str) {
						if (!sortflag) {//新消息


							if ($contentbox.find('#' + data_MessageList[0].id).length == 0) {

								$contentbox.find('.talk_con .mCSB_container>div').append(str);

								if (hasimgflag > 0) {//有图片

									var $imgs = $contentbox.find('.talk_con .mCSB_container>div').find('img');

									isImgLoad($imgs, function () {
										// $('#chatcontentlistbox #scrollbar-msg-'+tag).mCustomScrollbar("scrollTo","bottom",{timeout:0});
										$contentbox.find('[scrollbartag="' + userId_to + '"]').mCustomScrollbar("scrollTo", "bottom", {timeout: 0});


									});
								}
								else {
									//$('#chatcontentlistbox #scrollbar-msg-'+tag).mCustomScrollbar("scrollTo","bottom",{timeout:0});

									$contentbox.find('[scrollbartag="' + userId_to + '"]').mCustomScrollbar("scrollTo", "bottom", {timeout: 0});
								}

							}


						}
						else { //上拉加载历史记录
							if ($contentbox.find('#' + data_MessageList[data_MessageList.length - 1].id).length == 0) {
								linkdusertoid = $contentbox.find('.talk_con .mCSB_container>div .talk_time:eq(0)').attr('id');
								var height = (data_MessageList.length * 73 - 73) + 'px';

								//$('#chatcontentlistbox #scrollbar-msg-'+tag).mCustomScrollbar("scrollTo",height,{timeout:0});


								$contentbox.find('[scrollbartag="' + userId_to + '"]').mCustomScrollbar("scrollTo", height, {timeout: 0});
								$contentbox.find('.talk_con .mCSB_container>div').prepend(str);
							}
						}

						$contentbox.show().siblings().hide();

					}

				}
				else { //是切换对象时获取的数据,该聊天对象对应的msg-content不存在

					//首先要清除历史记录的localstorage


					$('.msg-content').hide();
					var $imlistul = $('.im_list_ul');

					var currentdata_control = $imlistul.attr('data-control');
					var datauserto = currentdata_control.split('-')[1];

					var $currentli = $imlistul.find('li[userto="' + datauserto + '"]');

					$currentli.addClass('list_bg').siblings('li').removeClass('list_bg');

					var currentnickname = $currentli.find('.im_list_name').attr('title');
					if (!currentnickname) {
						var $curlistbg = $('.im_list_ul .list_bg .im_list_name');
						if ($curlistbg.length > 0) {
							currentnickname = $curlistbg.attr('title');
						} else {
							//都没有,只能用缓存了
							var chatwin_house_user_to = $.cookie('chatwin_house_user_to');
							if (chatwin_house_user_to) {
								var ceruserto = chatwin_house_user_to.split('-')[1];
								if (ceruserto) {
									var $cli = $imlistul.find('li[userto="' + ceruserto + '"]');

									currentnickname = $cli.find('.im_list_name').attr('title');
									$cli.addClass('list_bg').siblings('li').removeClass('list_bg');


								}
							}

						}
					}


					var mcontent = '<div class="msg-content" msgusertag="' + userId_to + '"  id="msg-' + tag + '" style="display: block;">\n\
                                 <div class="im_user_infor noselect"  id="info-msg-' + tag + '" style="">\n\
                                    <div class="user_con">\n\
                                        <dl class="im_user_dl">\n\
                                            <dt><span class="IM-LinkmanInfoName" title="'+currentnickname+ '">' + $.i18n.prop('ffcbd4ac5d9c66983713ca44e667bc50') +' <span class="">'+currentnickname+'</span> '+$.i18n.prop('6303b939388bf0caf7af003c3567a13e')+'</span></dt>\n\
                                        </dl>\n\
                                     </div>\n\
                                 </div>\n\
                                 <div class="window_con">\n\
                                    <div class="talk_con IM-MsgList mCustomScrollbar _mCS_2" scrollbartag="' + userId_to + '" id="scrollbar-msg-' + tag + '"><div>';


					mcontent = mcontent + str + '</div></div></div></div>';
					$('.im_window').append(mcontent);


					if (hasimgflag > 0) {//有图片
						//var $imgs= $('#chatcontentlistbox #scrollbar-msg-'+tag).find('img');

						var $imgs = $('#chatcontentlistbox [scrollbartag="' + userId_to + '"]').find('img');

						isImgLoad($imgs, function (e) {

							// var height = $('.im_talk #scrollbar-msg-'+tag).children('div').height();

							var height = $('.im_talk [scrollbartag="' + userId_to + '"]').children('div').height();


							//$('#chatcontentlistbox #scrollbar-msg-'+tag).mCustomScrollbar({ setTop: '-'+height+'px',scrollInertia:'10',callbacks:{
							$('#chatcontentlistbox [scrollbartag="' + userId_to + '"]').mCustomScrollbar({
								mouseWheel: {preventDefault: true},
								setTop: '-' + height + 'px',
								scrollInertia: '10',
								callbacks: {
									onScroll: function () {


										//滚动结束
									},
									onTotalScrollBack: function () {
										//滚动到顶部

										_this.fetchOldMessage(houseId, userId_to, true);
									},
									onTotalScroll: function (event) {
										//             //滚动到底部的时候调用
										//             //禁用滚动条
										//
									}
								}
							});
						});

					}
					else {//没有图片


						var height = $('.im_talk [scrollbartag="' + userId_to + '"]').children('div').height();


						//$('#chatcontentlistbox #scrollbar-msg-'+tag).mCustomScrollbar({ setTop: '-'+height+'px',scrollInertia:'10',callbacks:{


						// var height = $('.im_talk #scrollbar-msg-'+tag).children('div').height();
						$('#chatcontentlistbox [scrollbartag="' + userId_to + '"]').mCustomScrollbar({
							mouseWheel: {preventDefault: true},
							setTop: '-' + height + 'px',
							scrollInertia: '10',
							callbacks: {
								onScroll: function () {
									//滚动结束
								},
								onTotalScrollBack: function () {
									//滚动到顶部

									_this.fetchOldMessage(houseId, userId_to, true);
								},
								onTotalScroll: function (event) {
									//             //滚动到底部的时候调用
									//             //禁用滚动条
									//
								}
							}
						});
					}


				}


				if (sortflag) {//上拉才会存储

					if (data_MessageList[0].id) {
						var historyten = localStorage.getItem("historyten");
						if (!historyten) {//没有存储过
							var historyten = {};
							// historyten.itemid= 'msg-content-'+houseId+'-'+userId_to; //id

							historyten.itemid = 'msg-content-' + userId_to; //id
							historyten.historycontent = str;//历史记录内容
							historyten.count = 1;//拉过一次
							historyten.lastchildid = data_MessageList[0].id;
							historyten.linkdusertoid = linkdusertoid;
							historyten.historycount = data_MessageList.length;//这次拉了多少条数据
							historyten = JSON.stringify(historyten);
							localStorage.setItem("historyten", historyten);

						}
						else {
							historyten = JSON.parse(historyten);

							//('msg-content-'+houseId+'-'+userId_to)
							if (historyten.itemid == ('msg-content-' + userId_to)) {//原本已存在
								historyten.itemid = historyten.itemid;
								historyten.linkdusertoid = linkdusertoid;
								historyten.historycontent = str;//历史记录内容
								historyten.count++;//拉过一次
								historyten.lastchildid = data_MessageList[0].id;
								historyten.historycount = data_MessageList.length;//这次拉了多少条数据
								historyten = JSON.stringify(historyten);
								localStorage.setItem("historyten", historyten);
							}
							else {//存的是别的聊天对象的,就当作没有存储过,覆盖
								var historyten = {};
								// historyten.itemid= 'msg-content-'+houseId+'-'+userId_to; //id

								historyten.itemid = 'msg-content-' + userId_to; //id
								historyten.historycontent = str;//历史记录内容
								historyten.count = 1;//拉过一次
								historyten.lastchildid = data_MessageList[0].id;
								historyten.historycount = data_MessageList.length;//这次拉了多少条数据
								historyten.linkdusertoid = linkdusertoid;
								historyten = JSON.stringify(historyten);
								localStorage.setItem("historyten", historyten);
							}


						}
					}
				}

			}
			catch (e) {
				console.log(e)
			}

		},

		/*
     * 发布消息接口
     */
		pushOneMessage: function (messageOther, type, obj) {
			var _this = this;
			var con = $('.im_list_ul').attr('data-control');
			var cona = con.split("-");
			var param = {};
			var message = '';
			if (messageOther) {
				message = messageOther;
			}
			else if (type == 'recommend') {
				message = obj.message;
			}
			else {
				message = $('#IM-TextareaContent').val().trim();
			}

			if (message.length != 0) {
				param.userId_from = jQuery.cookie("id");
				param.userId = jQuery.cookie("id");
				param.yyoh = $.cookie("yyoh");
				param.channelId = '4887233339966371802';
				param.houseId = cona[0];
				param.baiduId = '760580008275051542';
				param.userId_to = cona[1];
				param.subjectType = 0;
				param.message = message;
				/*var myDate = new Date();
                var month = (parseInt(myDate.getMonth())+1);
                month = ((month>9)?month:('0'+month));
                var date = month+"-"+((myDate.getDate()>9)?myDate.getDate():('0'+myDate.getDate()))+' '+((myDate.getHours()>9)?myDate.getHours():('0'+myDate.getHours()))+':'+((myDate.getMinutes()>9)?myDate.getMinutes():('0'+myDate.getMinutes()))+':'+((myDate.getSeconds()>9)?myDate.getSeconds():('0'+myDate.getSeconds()));
                message = message.replace(new RegExp("<","g"),"&lt;");
                message = message.replace(new RegExp(">","g"),"&gt;");
                console.log('1111111');
                console.log(date);
                console.log('1111111');*/
				if (type == 'recommend') {
					Object.assign(param, obj);
					/*param.recommendHouseId = obj.recommendHouseId;
                    param.recommendHouseTitle = obj.recommendHouseTitle;
                    param.recommendHouseCurrency = obj.recommendHouseCurrency;
                    param.recommendHousePrice = obj.recommendHousePrice;
                    param.recommendHousePicture = obj.recommendHousePicture;
                    param.recommendHouseRoomType = obj.recommendHouseRoomType;
                    param.recommendHouseAccommodateNum = obj.recommendHouseAccommodateNum;*/
				} else {
					$('#IM-TextareaContent').val('');
				}
				var value = JSON.stringify(param);
				//进行发送消息
				treatData('pushMessage/pushOneMessage', value, function (data, url) {
					if (data.status.status_code == 0) {
						/*console.log('2222222');
                        console.log(date);
                        console.log('2222222');*/
						//获取当前在线页面信息
						var chatCurrentPage = store.get('chatCurrentPage');
						if (chatCurrentPage) {
							if (chatCurrentPage.length > 1) {
								var sharePushMessageData = store.get('sharePushMessageData');
								if (!sharePushMessageData || sharePushMessageData == 'undefined') {
									//没有共享数据的时候
									var sharePushMessageData = [{
										id: data.result.ReturnTimeAndMsgKey.messageId,
										msgKey: data.result.ReturnTimeAndMsgKey.msgKey,
										publishTime: data.result.ReturnTimeAndMsgKey.date,
										house_user_to: param.houseId + '-' + param.userId_to,
										message: message,
										saveTime: new Date().getTime()
									}];
								} else {
									//有共享数据的时候
									sharePushMessageData.push({
										id: data.result.ReturnTimeAndMsgKey.messageId,
										msgKey: data.result.ReturnTimeAndMsgKey.msgKey,
										publishTime: data.result.ReturnTimeAndMsgKey.date,
										house_user_to: param.houseId + '-' + param.userId_to,
										message: message,
										saveTime: new Date().getTime()
									});
								}
								store.set('sharePushMessageData', sharePushMessageData);
							} else {
								//直接删除全部存储的历史聊天记录
								store.remove('sharePushMessageData');
							}
						}

                        //将内容写入上边边框中(暂时注销)
                        var time = data.result.ReturnTimeAndMsgKey.date.substring(5, 19);
                        var str = '<p class="talk_time" id="'+data.result.ReturnTimeAndMsgKey.messageId+'" style="display: block;">'+time+'</p>';
                        if(type == 'recommend'){
                            var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'),$.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'),$.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'),$.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                            var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                            var currency_symbol = currency_symbol_arr[obj.recommendHouseCurrency-1].symbol || '';
                            str += '<div class="box white_bg" id="'+data.result.ReturnTimeAndMsgKey.msgKey+'">' +
                                '<a href="'+obj.message+'" target="_blank">' +
                                '<img src="'+obj.recommendHousePicture+'"/>' +
                                '<div class="houseInfo">' +
                                '<p>'+obj.recommendHouseTitle+'</p>' +
                                '<p>'+roomType[obj.recommendHouseRoomType]+$.i18n.prop('c538296dc5ff5b40f5554066b4f2c5e0')+obj.recommendHouseAccommodateNum+$.i18n.prop('90df1fbdc4fc7f458bcf74422f426a60') +'</p>' +
                                '<p>'+currency_symbol+Math.round(obj.recommendHousePrice)+'</p>' +
                                '</div>' +
                                '</a>' +
                                '<span></span>' +
                                '</div>'
                        }else{
                            str = str + '<div class="box red_bg" id="'+data.result.ReturnTimeAndMsgKey.msgKey+'">\n\
                                    <div>'+message+'</div>\n\
                                    <span></span>\n\
                                </div>';
						}


                        if(data.result.ReturnTimeAndMsgKey.messageType=='-2'){
                                str=str+'<p class="sensewarn">' + $.i18n.prop('20b07050b384497c951b497263d01d26') + '</p>';
                        }

						var $scrollbarmsgcontent = $('#scrollbar-msg-content-' + cona[0] + '-' + cona[1]);
						if ($scrollbarmsgcontent.length > 0) {
							if ($scrollbarmsgcontent.find('#' + data.result.ReturnTimeAndMsgKey.messageId).length <= 0)
								$scrollbarmsgcontent.children('.mCustomScrollBox').children('.mCSB_container').children('div').append(str);


						}

						$('#chatcontentlistbox #scrollbar-msg-content-' + cona[0] + '-' + cona[1]).mCustomScrollbar("scrollTo", "bottom", {timeout: 500});


						if (messageOther) {
							$('.im_operater').show();
							$('.im_clanbox').hide();
						}

                    }else{
                        //这里如果发送失败，就直接显示失败，用户可以重新发送
                        $('#nickName').val(data.url);
                        alert($.i18n.prop('bbfac194b8833364d3f825db714b0847'));
                    }
                });
            }
        // }
     },
       // 监听客服等各种弹窗的拖动
     onDraggableFun: function(id){

			try {
				$(id).draggable({
					stack: '#IM-Chatwin,.service-box,#recommend-house', // 当停止拖拽时，最后一个被拖拽的项目总是出现在同组其他项目的上面
					addClasses: false,//禁止加载jquery ui样式,没有用到jquery ui原本的样式,防止可提升效率
					containment: 'body',//只在文档内拖动
					scroll: false,
					opacity: 0.98,//拖动时聊天框的不透明度
					cursor: 'move',
					handle: '.service-box-top-nav',//可拖动的元素
					stop: function (event, ui) {//拖动成功,释放鼠标时触发
						if ($(id).is(":hidden") == false) {
							var $imchatwin = $("#IM-Chatwin");
							var xbox = $imchatwin.css("left").replace('px', '');
							var ybox = $imchatwin.css("top").replace('px', '');
							var $body = $(window);
							var bodywidth = $body.width();
							var bodyheight = $body.height();
							var width = $imchatwin.width();
							var height = $imchatwin.height();

							if (xbox < 0 || ybox < 0) {
								if (xbox < 0) {
									xbox = 0;
									$imchatwin.css("left", '0');
								}
								if (ybox < 0) {
									ybox = 0;
									$imchatwin.css("top", '0');
								}
							}

							if (bodyheight - parseInt(ybox) < 50) {
								ybox = bodyheight - 50;
								$imchatwin.css("top", ybox + 'px');

							}

							jQuery.cookie("servicechatwin_positioning", xbox + '_' + ybox, {path: "/"});
						}
					}

				});
			}
			catch (e) {
			}
		},

		/*
     * 注册监听动作，已进入页面的时候就进行
     */
		registerMonitorAction: function () {
			var _this = this;

			try {
				$("#IM-Chatwin").draggable({
					stack: '#IM-Chatwin,.service-box,#recommend-house', // 当停止拖拽时，最后一个被拖拽的项目总是出现在同组其他项目的上面
					addClasses: false,//禁止加载jquery ui样式,没有用到jquery ui原本的样式,防止可提升效率
					containment: 'body',//只在文档内拖动
					scroll: false,
					opacity: 0.98,//拖动时聊天框的不透明度
					cursor: 'move',
					handle: '#IM-UserPre,.im_user_infor,.im_room_tabsbox,.cur_room_info2',//可拖动的元素
					stop: function (event, ui) {//拖动成功,释放鼠标时触发
						if ($("#IM-Chatwin").is(":hidden") == false) {
							var $imchatwin = $("#IM-Chatwin");
							var xbox = $imchatwin.css("left").replace('px', '');
							var ybox = $imchatwin.css("top").replace('px', '');
							var $body = $(window);
							var bodywidth = $body.width();
							var bodyheight = $body.height();
							var width = $imchatwin.width();
							var height = $imchatwin.height();

							if (xbox < 0 || ybox < 0) {
								if (xbox < 0) {
									xbox = 0;
									$imchatwin.css("left", '0');
								}
								if (ybox < 0) {
									ybox = 0;
									$imchatwin.css("top", '0');
								}
							}

							if (bodyheight - parseInt(ybox) < 50) {
								ybox = bodyheight - 50;
								$imchatwin.css("top", ybox + 'px');

							}

							jQuery.cookie("chatwin_positioning", xbox + '_' + ybox, {path: "/"});
						}
					}

				});
			}
			catch (e) {
			}


			//点击聊天列表切换聊天对象
			$('.im_list_ul').on('click', 'li', function () {

				try {
					$('#IM-Chatwin').attr('setscrolltopflag', '1');//左侧聊天列表是否设置重设scrolltop

					store.remove('houseMessageListSwitch');

					$('.im_operater').show();
					$('.im_clanbox').hide();

					localStorage.removeItem("historyten");
					//将上一个关闭的窗口的top值记录下来
					var currentTag = $('.im_list_ul').attr('data-control');
					var currentTop = $('#scrollbar-msg-content-' + currentTag).children('.mCustomScrollBox').children('.mCSB_container').css('top');

					//$('#scrollbar-msg-content-'+currentTag).attr('data-scroll-top',currentTop);
					//修改相关样式
					$('.im_list_ul li').removeClass('list_bg');
					var $this = $(this);
					$this.addClass('list_bg');


					var im_list_ulscrolltop = $('#im_ul_wrapper>.mCustomScrollBox>.mCSB_container').css('top');
					if (im_list_ulscrolltop) {
						$.cookie("im_list_ulscrolltop", im_list_ulscrolltop, {"expires": 1, path: "/"});

						$.cookie("ulscrolltop", im_list_ulscrolltop, {"expires": 1, path: "/"});
					}

					var con = $this.attr('id');
					var cona = con.split("-");
					var houseId = cona[2];
					var userId_to = cona[3];


					var $msgcontent = $('#chatcontentlistbox .msg-content[msgusertag="' + userId_to + '"]');
					//console.log('原聊天框:'+$msgcontent.length);

					if ($msgcontent.length > 0) {
						//如果对方将房源修改了,这边切换的时候也要切换到相应的房源

						var chatid = $this.attr('id');
						var oldhouseid = chatid.split('plug-chat-')[1];
						oldhouseid = oldhouseid.split('-')[0];

						var newhouseid = $this.attr('newhouseid');

						var $plughouse = $('#IM-LodgeUnitShow .plug-curlu[useridto="' + userId_to + '"]');

						var oldplughouseid = $plughouse.attr('id');
						var houseuser = oldplughouseid.split('plug-curlu-')[1];
						var plughouse = houseuser.split('-')[0];

						var flag = false;

						var subid = '';

						if (!newhouseid) {
							if (plughouse == oldhouseid && $this.attr('lihouseid') == oldhouseid) {
								flag = true;
							}
							else if (plughouse != oldhouseid) {
								subid = oldhouseid;
							} else if ($this.attr('lihouseid') != oldhouseid) {
								subid = $this.attr('lihouseid');
							}
						}
						else {
							if ((newhouseid == oldhouseid && oldhouseid == plughouse && $this.attr('lihouseid') == oldhouseid)) {
								flag = true;
							}
							else if (newhouseid != oldhouseid) {
								subid = newhouseid;
							} else if (oldhouseid != plughouse) {
								subid = oldhouseid;
							}
							else if ($this.attr('lihouseid') != oldhouseid) {
								subid = $this.attr('lihouseid');
							}

						}


						if (flag) {//没修改房源
							//console.log('没有新房源');
							$('.plug-curlu').hide();

							$this.removeAttr('newhouseid');

							var $plughouse = $('#IM-LodgeUnitShow .plug-curlu[useridto="' + userId_to + '"]');

							if ($plughouse.length > 0) {
								$plughouse.show();
								$('.nohousebox').hide();
							} else {
								$('.nohousebox').show();
							}
						}
						else {//修改了房源
							//console.log('切换了新房源');
							var samelorder_id = $this.attr('id');
							var samehouserIduserId = samelorder_id.split('plug-chat-')[1];

							var $chatcontent = $('#chatcontentlistbox #msg-content-' + samehouserIduserId);

							// var newhouseid=($this.attr('lihouseid')!=oldhouseid)?$this.attr('lihouseid'):newhouseid;
							//  if(plughouse!=oldhouseid)
							//      newhouseid=$this.attr('lihouseid');


							newhouseid = subid;
							//console.log('newhouseid:'+newhouseid);

							$this.attr('id', 'plug-chat-' + newhouseid + '-' + userId_to);

							if ($chatcontent.length > 0) {//右边的聊天内容栏也要改
								$chatcontent.attr('id', 'msg-content-' + newhouseid + '-' + userId_to);
								$chatcontent.find('.im_user_infor').attr('id', 'info-msg-content-' + newhouseid + '-' + userId_to);
								$chatcontent.find('.talk_con').attr('id', 'scrollbar-msg-content-' + newhouseid + '-' + userId_to);
							}

							$('#IM-LodgeUnitShow .plug-curlu[useridto="' + userId_to + '"]').remove()
							//console.log('触发了remove');

							_this.getHouseInfo(newhouseid, userId_to);

							$('#plug-curlu-' + newhouseid + '-' + userId_to).show().siblings().hide();


							houseId = newhouseid;

							$this.removeAttr('newhouseid');

						}

					} else {
						_this.getHouseInfo(houseId, userId_to);
					}


					//将当前会话窗口保存到cookie中
					jQuery.cookie("chatwin_house_user_to", houseId + '-' + userId_to, {path: "/"});
					jQuery.cookie("chatwin_userId_to", userId_to, {path: "/"});
					//给外层控制台设置当前要获取的聊天对话
					$(this).parent().attr('data-control', houseId + '-' + userId_to);

					//将未读消息的标识去掉
					var $close = $(this).find('.close');
					if ($close.hasClass('unreadCount')) {
						$close.removeClass('unreadCount').find('span').html('');
						_this.notifyOneSessionHasReadToServer(userId_to);//把当前会话对象的消息设置为已读
					}


					//获取历史聊天信息

					var $msgcontentc = $('#chatcontentlistbox .msg-content[msgusertag="' + userId_to + '"]');
					if ($msgcontentc.length > 0) {
						$('.msg-content').hide();
						$msgcontentc.show();

						_this.getMessageList();

						$('#chatcontentlistbox .mCustomScrollbar[scrollbartag="' + userId_to + '"]').mCustomScrollbar('scrollTo', "bottom", {scrollInertia: -4});

						// var nextTop = $('#scrollbar-msg-content-'+houseId+'-'+userId_to).attr('data-scroll-top');
						// nextTop = parseInt(nextTop);
						// if(nextTop){
						//     $('#scrollbar-msg-content-'+houseId+'-'+userId_to).mCustomScrollbar( 'scrollTo',[nextTop,0] ,{scrollInertia:0});
						// }else{
						//     $('#scrollbar-msg-content-'+houseId+'-'+userId_to).mCustomScrollbar( 'scrollTo', "bottom" ,{scrollInertia:0});
						// }


					} else {

						_this.fetchOldMessage(houseId, userId_to);
					}

					var timestamp = new Date().getTime();

					//重新开启新的列表查询
					window.clearInterval(_this.opts.chatUserList);
					window.clearInterval(_this.opts.chatUserList_wait);
					_this.opts.chatUserList = window.setInterval(function () {
						_this.checkMessageList(houseId, userId_to)
					}, 5000);


					//如果是重新打开别人的聊天窗口
					var href = window.location.href;
					if (!jQuery.cookie("chatwin_prev_house_user_to")) {
						// _this.checkChatInfo('on',houseId,userId_to)
					} else if (jQuery.cookie("chatwin_prev_house_user_to") != (href + houseId + '-' + userId_to)) {
						jQuery.cookie("chatwin_prev_house_user_to", href + houseId + '-' + userId_to, {path: "/"});
						// _this.checkChatInfo('on',houseId,userId_to)
					}
					//获取房源信息


				}
				catch (e) {

				}


			});


			//点击关闭按钮，隐藏聊天框
			$('.im_btn_close').click(function () {
				var $this = $(this);

				$('.im_list_ul').attr('data-control', '1-1');
				jQuery.cookie("chatwin_overflow", 'hidden', {path: "/"});
				jQuery.cookie("chatwin_prev_house_user_to", null, {"expires": -1, path: "/"});

				dialogOption($this);
			});
			// 点击打开或者关闭聊天框(跟canvas重复,到时候留一个)
			$('.im_M.IM-BtnMouse-Msg').click(function () {

				try {
					if (!jQuery.cookie("yyoh") || !jQuery.cookie("id")) {
						var history = window.location.pathname + window.location.search;
						history = history.length ? ('?history=' + history) : '';
						window.location.href = "/login/p_login" + history;
						return;
					}
					var $this = $(this);
					$.cookie("openedchatbox", '1', {"expires": 1, path: "/"});
					$('.im_operater').show();
					$('.im_clanbox').hide();

					var haslist = $('.im_list_ul li');


					if (!jQuery.cookie("chatwin_overflow") || jQuery.cookie("chatwin_overflow") == 'hidden') {

						// jQuery.cookie("hasMessageList",'false',{"expires":1,path:"/"});
						if (!jQuery.cookie("hasMessageList")) {
							$("#IM-Chatwin,.recommend-house").hide();
							$('#messlist-box').show();
							$('.im_L.im_M.im_new_L.im_new_M.im_new_hover').addClass('open');
						} else {
							//重新进行外部循环搜索（关掉当前循环，直接进行搜索，然后再次打开循环搜索）
							_this.getMessageList();

							//如果是空的话就隐藏
							jQuery.cookie("chatwin_overflow", 'show', {path: "/"});
							jQuery.cookie("im_news_overflow", jQuery.cookie("id") + '-show', {
								"expires": 1000,
								path: "/"
							});


							//打开聊天框
							if (jQuery.cookie("chatwin_positioning")) {
								var position = jQuery.cookie("chatwin_positioning");
								var cona = position.split("_");
								var chat_x = cona[0];
								var chat_y = cona[1];
								$("#IM-Chatwin").css({top: chat_y + 'px', left: chat_x + 'px'});
							} else {
								var height = $(window).height();
								var width = $(window).width();
								// $("#IM-Chatwin").css({ top: (height-500)/2+'px', left: (width-788)/2+'px'});
								$("#IM-Chatwin").css({bottom: '68px', right: '340px'});
							}

							$('#IM-Chatwin').attr('setscrolltopflag', '1');//左侧聊天列表是否设置重设scrolltop


							// $("#IM-Chatwin").show();
							// $('#messlist-box').hide();

							window.clearInterval(_this.opts.chatUserList);
							window.clearInterval(_this.opts.chatUserList_wait);
							_this.opts.chatUserList = window.setInterval(function () {
								_this.checkMessageList()
							}, 5000);
							//重新查询聊天信息
							// var cona = $('.im_list_ul').attr('data-control').split("-");
							// var houseId = cona[0];
							// var userId_to = cona[1];


							var $list_bg = $('#im_ul_wrapper .im_list_ul .list_bg');
							if ($list_bg.length > 0) {

								//如果对方将房源修改了,这边切换的时候也要切换到相应的房源

								var chatid = $list_bg.attr('id');
								var oldhouseid1 = chatid.split('plug-chat-')[1];
								var oldhouseid = oldhouseid1.split('-')[0];

								var userId_to = oldhouseid1.split('-')[1];

								var newhouseid = $list_bg.attr('newhouseid');

								var $plughouse = $('#IM-LodgeUnitShow .plug-curlu[useridto="' + userId_to + '"]');

								var oldplughouseid = $plughouse.attr('id');
								var houseuser = oldplughouseid.split('plug-curlu-')[1];
								var plughouse = houseuser.split('-')[0];

								var flag = false;

								var subid = '';

								if (!newhouseid) {
									if (plughouse == oldhouseid && $list_bg.attr('lihouseid') == oldhouseid) {
										flag = true;
									}
									else if (plughouse != oldhouseid) {
										subid = oldhouseid;
									} else if ($list_bg.attr('lihouseid') != oldhouseid) {
										subid = $list_bg.attr('lihouseid');
									}
								}
								else {
									if ((newhouseid == oldhouseid && oldhouseid == plughouse && $list_bg.attr('lihouseid') == oldhouseid)) {
										flag = true;
									}
									else if (newhouseid != oldhouseid) {
										subid = newhouseid;
									} else if (oldhouseid != plughouse) {
										subid = oldhouseid;
									}
									else if ($list_bg.attr('lihouseid') != oldhouseid) {
										subid = $list_bg.attr('lihouseid');
									}

								}


								if (flag) {//没修改房源
									//console.log('没有新房源');
									$('.plug-curlu').hide();

									$list_bg.removeAttr('newhouseid');

									var $plughouse = $('#IM-LodgeUnitShow .plug-curlu[useridto="' + userId_to + '"]');

									if ($plughouse.length > 0) {
										$plughouse.show();
										$('.nohousebox').hide();
									} else {
										$('.nohousebox').show();
									}
								}
								else {//修改了房源
									//console.log('切换了新房源');
									var samelorder_id = $list_bg.attr('id');
									var samehouserIduserId = samelorder_id.split('plug-chat-')[1];

									var $chatcontent = $('#chatcontentlistbox #msg-content-' + samehouserIduserId);


									newhouseid = subid;
									//console.log('newhouseid:'+newhouseid);

									$list_bg.attr('id', 'plug-chat-' + newhouseid + '-' + userId_to);

									if ($chatcontent.length > 0) {//右边的聊天内容栏也要改
										$chatcontent.attr('id', 'msg-content-' + newhouseid + '-' + userId_to);
										$chatcontent.find('.im_user_infor').attr('id', 'info-msg-content-' + newhouseid + '-' + userId_to);
										$chatcontent.find('.talk_con').attr('id', 'scrollbar-msg-content-' + newhouseid + '-' + userId_to);
									}

									$('#IM-LodgeUnitShow .plug-curlu[useridto="' + userId_to + '"]').remove();
									//console.log('触发了remove');

									_this.getHouseInfo(newhouseid, userId_to);

									$('#plug-curlu-' + newhouseid + '-' + userId_to).show().siblings().hide();


									houseId = newhouseid;

									$list_bg.removeAttr('newhouseid');

								}


							}

							dialogOption($this);
						}


					} else {

						if (!jQuery.cookie("hasMessageList")) {
							$("#IM-Chatwin,.recommend-house").hide();
							$('#messlist-box').show();
							$('.im_L.im_M.im_new_L.im_new_M.im_new_hover').addClass('open');
						} else {
							//继续查询消息
							_this.getMessageList();

							$('.im_list_ul').attr('data-control', '1-1');
							jQuery.cookie("chatwin_overflow", 'hidden', {path: "/"});
							jQuery.cookie("chatwin_prev_house_user_to", null, {"expires": -1, path: "/"});

							// $("#IM-Chatwin").hide();
							// $('#messlist-box').hide();
							//关闭聊天信息查询
							// _this.checkChatInfo('off');

							window.clearInterval(_this.opts.chatUserList);
							window.clearInterval(_this.opts.chatUserList_wait);
							_this.opts.chatUserChat = 0;
							_this.opts.chatUserList_wait = 0;
							_this.opts.chatUserList = window.setInterval(function () {
								_this.checkMessageList()
							}, 5000);

							dialogOption($this);
						}

					}


				}
				catch (e) {

				}

			});

			//点击enter键发送数据
			$("html").on("keydown", function (event) {
				if ($('#IM-TextareaContent').is(":focus")) {
					if (event.ctrlKey && event.keyCode == 13) {
						$('#IM-TextareaContent').val($('#IM-TextareaContent').val() + '\n');
					} else if (event.keyCode == 13) {
						//直接发送消息
						_this.pushOneMessage();
						event.returnValue = false;
						return false;
					}
				}
			});


			//鼠标悬浮时出现删除按钮
			$('.im_list_ul').on({
				'mouseenter': function (e) {
					var $target = $(e.target);
					var $this = $(this);
					$this.find('.deleteicon').show();
				},
				'mouseleave': function (e) {
					var $this = $(this);
					$this.find('.deleteicon').hide();
				}

			}, 'li')


			//删除按钮事件
			$('.im_list_ul').on('click', '.deleteicon', function (e) {
				try {
					e.stopPropagation();
					var $this = $(this).parents('li');

					// var con = $this.attr('id');
					// var cona = con.split("plug-chat-");
					// cona = cona[1];
					var userId_to = $this.attr('userto');

					var tempchat = $.cookie('temporary_chat');


					var param = {};
					param.yyoh = $.cookie("yyoh");
					param.userId = $.cookie("id");
					param.isTestApi = '';//值为1时表示数据桩
					param.userId_to_id = userId_to;//聊天对象的id
					param.type = 2;//标示是删除


					var new_chat = [];
					if (jQuery.cookie("temporary_chat")) {//从临时聊天中删除
						var old_chat = jQuery.cookie("temporary_chat");
						var chatArr = JSON.parse(old_chat);
						for (var i = 0; i < chatArr.length; i++) {
							//判断是否过期
							if ((chatArr[i].userId == jQuery.cookie("id")) && (chatArr[i].userId_to_id != userId_to)) {
								var attr = {
									"nickName": chatArr[i].nickName,
									"userId_to_id": chatArr[i].userId_to_id,
									"userId": chatArr[i].userId,
									"houseId": chatArr[i].houseId,
									"headUrl": chatArr[i].headUrl,
									"readYN": chatArr[i].readYN,
									"readNo": chatArr[i].readNo,
									"publish_time": chatArr[i].publish_time,
									"survival": chatArr[i].survival
								};

								new_chat.push(attr);

							}
						}
						if (new_chat.length > 0) {
							var temporary = JSON.stringify(new_chat);
							jQuery.cookie("temporary_chat", temporary, {"expires": 1, path: "/"});
						} else {
							jQuery.cookie("temporary_chat", null, {"expires": -1, path: "/"});
						}
					}


					var value = JSON.stringify(param);
					treatData('pushMessage/topAndDeletedSession', value, function (data, url) {
						try {
							if (data.status.status_code == 0) {
								var $next = $this.next();
								var $prev = $this.prev();

								if ($next.length)
									$next.click();
								else if ($prev.length) {
									$prev.click();
								}
								else {
									$("#IM-Chatwin,.recommend-house").hide();
								}


								$this.remove();
							}
						}
						catch (e) {
							console.log(e)
						}


					});

					// 没有了聊天对象,全部删除了,就设置 为空
					if (!jQuery.cookie("temporary_chat")) {
						$('.im_L.im_M.im_new_L.im_new_M.im_new_hover').removeClass('open');
						jQuery.cookie("hasMessageList", '', {"expires": 1, path: "/"});
						//如果是空的话就隐藏
						jQuery.cookie("chatwin_overflow", 'hidden', {path: "/"});
					}
				} catch (e) {
				}


				//plug-chat-'+chatList[i].houseId+'-'+chatList[i].userId_to_id

			})


			//聊天 点击"开始咨询"
			$('.im_clanbox').on('click', '#clan_consult', function () {
				$('.warnclan').hide();
				var $this = $(this);

				var startdate = $('#clan_start').attr('data-time');//20140404
				var enddate = $('#clan_end').attr('data-time');//20140404

				$.cookie(window.location.pathname + "startdatechat", startdate, {
					path: "/", expiress: 1
				})
				$.cookie(window.location.pathname + "enddatechat", enddate, {
					path: "/", expiress: 1
				})

				var peoplenum = $('#chan_accommodateNum').attr('numvalue');
				if (!peoplenum)
					peoplenum = 1;
				if (!startdate || !enddate) {
					$('.warnclan').show();
					return;
				}

				$this.attr('disabled', 'disabled');


				var setorderparam = {};

				var con = $('.im_list_ul').attr('data-control');
				var cona = con.split("-");
				setorderparam.userId = jQuery.cookie("id");
				setorderparam.yyoh = $.cookie("yyoh");
				setorderparam.endDate = enddate;
				setorderparam.startDate = startdate;
				setorderparam.type = '1';
				setorderparam.houseId = cona[0];
				setorderparam.peopleNum = peoplenum;

             var message=$.i18n.prop('bc7e2a80630a801abd4a2aadd5b6ee0d')+startdate.substr(4,2)+$.i18n.prop('b6403422632f17362dfc46015e16320a')+startdate.substr(6,2)+$.i18n.prop('276cdccf942f2fa5d5e979c4158bf851')+enddate.substr(4,2)+$.i18n.prop('b6403422632f17362dfc46015e16320a')+enddate.substr(6,2)+$.i18n.prop('010b563f34fbd1e53b7136bdc091ee3a')+peoplenum+$.i18n.prop('df2d69fe8add7ae23be7d2e8f7c91e43');

				var value = JSON.stringify(setorderparam);
				try {
					treatData('order/setOrderConsultInfo', value, function (data, url) {

						if (data.status.status_code == 0) {//设置成功
							_this.pushOneMessage(message);
						}

						$this.removeAttr('disabled');
					});
				}
				catch (e) {
					$this.removeAttr('disabled');
				}


			})
			//聊天 点击发送
			$('#IM-SendChat').on('click', function () {
				_this.pushOneMessage();
			})

			//推荐房源 点击发送
			$('#recommend-house').on('click', '.recommend-btn', function () {
				var list = $(this).parents('li');
				var param = {
					message: window.location.protocol + '//' + window.location.host + '/h/' + list.attr('houseid'),
					recommendHouseId: list.attr('houseid'),
					recommendHouseTitle: list.attr('title'),
					recommendHouseCurrency: list.attr('currency'),
					recommendHousePrice: list.attr('price'),
					recommendHousePicture: list.attr('picture'),
					recommendHouseRoomType: list.attr('roomtype'),
					recommendHouseAccommodateNum: list.attr('accommodatenum')
				};
				_this.pushOneMessage('', 'recommend', param);
			})

			//初始化是否开启人工客服
			if($.cookie('serviceStatus') == 'on'){
				$('.service-box-top-nav-sub .openOnlineService').attr('data-status','on').html($.i18n.prop('8639934069c0f4f1b0b6b069128fd59a'));
			};

			//客服
			$('#service_send').on('click', function () {
				var serviceStatus = $.cookie('serviceStatus');
				if(serviceStatus && serviceStatus == 'on'){//人工客服
					_this.pushOneServiceMessage();
					_this.SetcloseConsultTimer();
				}else{
					_this.pushOneFAQTerm();
				}
			});

			//客服窗口常见问题列表点击事件
			$('.service-message-list-box').on('click', '.service-message-item.faqs .faqItem', function () {
				var id = $(this).attr('data-id');
				var param = {
					yyoh: $.cookie('yyoh'),
					userId: $.cookie('id'),
					question_id: id
				};
				var value = JSON.stringify(param);
				treatData('consult/getConsultFAQAnswerById', value, function (data) {
					if (data.status.status_code == 0) {
						_this.getMessageList();
					} else {
						alert(data.status.status_reason);
					}
				})

			});

			//开启人工服务
			$('.service-box').on('click','.openOnlineService',function(){
				var serviceStatus = $.cookie('serviceStatus');
				var openOnlineServiceBtn = $('.service-box-top-nav-sub .openOnlineService');
				if(openOnlineServiceBtn.attr('data-status') == 'off' || serviceStatus == 'off'){
					var now = new Date(),
						y = now.getFullYear(),
						m = now.getMonth()+1 < 10 ? '0'+(now.getMonth()+1) : now.getMonth()+1,
						d = now.getDate() < 10 ? '0'+now.getDate() : now.getDate(),
						start = y+'/'+m+'/'+d+' 09:00:00',
						end = y+'/'+m+'/'+d+' 18:30:00';
					if(Date.parse(now) >= Date.parse(start) && Date.parse(now) <= Date.parse(end)){
						$('.service-message-list-pack .mCSB_container').append('<div class="service-message-item-box assigning">' +
							'   <div class="service-message-item-prompt">' +
							'       <div class="service-message"><img src="/images/publish/uploading.png" class="animation_rorate align_t mR5"/><span class="align_t">正在分配客服</span></div>' +
							'   </div>' +
							'   <div class="clear"></div>' +
							'</div>');
						_this.messageListScrollBottom();

						var param = {
							yyoh: $.cookie('yyoh'),
							userId: $.cookie('id')
						};
						var value = JSON.stringify(param);
						treatData('pushMessage/getConsultantList',value,function(data){
							$('.service-message-item-box.assigning').remove();
							if(data.status.status_code == 0){
								if(data.result.consultantList.length && data.result.consultantList.length>0){
									$.cookie('serviceStatus','on');
									openOnlineServiceBtn.attr('data-status','on').html($.i18n.prop('8639934069c0f4f1b0b6b069128fd59a'));
									$('.service-message-list-pack .mCSB_container').append('<div class="service-message-item-box">' +
										'   <div class="service-message-item-prompt">' +
										'       <div class="service-message">已切换到人工客服，请输入您的问题哦</div>' +
										'   </div>' +
										'   <div class="clear"></div>' +
										'</div>');
									_this.messageListScrollBottom();

									// 发送给服务端通知,告诉我打开客服窗口了
									_this.addFirstConsultMessage();

									_this.SetcloseConsultTimer();
								}else{
									$('.service-message-list-pack .mCSB_container').append('<div class="service-message-item-box">' +
										'   <div class="service-message-item-prompt">' +
										'       <div class="service-message">'+$.i18n.prop('ab496c8b3e07a6dee2e2601013898306')+'<span class="color_ff6766 cursor_po openOnlineService">'+$.i18n.prop('3333d84ac619f3bd17e651e4c82a400d')+'</span></div>' +
										'   </div>' +
										'   <div class="clear"></div>' +
										'</div>');
									_this.messageListScrollBottom();
								}
							}else{
								alert(data.status.status_reason);
							}
						});
					}else{
						$('.service-message-list-pack .mCSB_container').append('<div class="service-message-item-box">' +
							'   <div class="service-message-item-prompt">' +
							'       <div class="service-message" style="line-height: 16px;">'+$.i18n.prop('ab496c8b3e07a6dee2e2601013898306')+'<br/>'+$.i18n.prop('771895e6c62659ea5f291777768e9e38')+'：400770111</div>' +
							'   </div>' +
							'   <div class="clear"></div>' +
							'</div>');
						_this.messageListScrollBottom();
					}
				}else{
					if($(this).parent().hasClass('service-box-top-nav-sub')){
						$.cookie('serviceStatus','off');
						$(this).attr('data-status','off').html($.i18n.prop('3333d84ac619f3bd17e651e4c82a400d'));
						clearTimeout(closeConsultTimer);
						$('.service-message-list-pack .mCSB_container').append('<div class="service-message-item-box">' +
							'   <div class="service-message-item-prompt">' +
							'       <div class="service-message" style="line-height: 16px;">'+$.i18n.prop('40bfe5662eff973e82440b406de428e1')+'</div>' +
							'   </div>' +
							'   <div class="clear"></div>' +
							'</div>');
						_this.messageListScrollBottom();
					}
				}
			});

			_this.shareHistoryMessage();//打开历史记录共享轮询

		},

		/***将某个聊天对象的消息设置为已读***/
		notifyOneSessionHasReadToServer: function (userId_to_id) {
			if (!userId_to_id)
				return;

			var _this = this;
			var param = {};
			param.yyoh = jQuery.cookie("yyoh");
			param.userId = jQuery.cookie("id");
			param.userId_to_id = userId_to_id;

			if ($('#IM-Chatwin').is(':visible')) {
				var value = JSON.stringify(param);
				treatData('pushMessage/notifyOneSessionHasReadToServer', value, function (data, url) {
					if (data.status.status_code == 0) {//设置成功
						var $unreadCount = $('.im_list_ul li[userto=' + userId_to_id + ']').find('.unreadCount');
						if ($unreadCount.length > 0) {
							$unreadCount.removeClass('unreadCount').find('span').html('');
						}
					}
				});
			}


		},


		/****
		 * 以下是客服逻辑
		 */


		/*
     * 查询旧的历史客服消息接口
     */
		checkOldServiceMessageAction: function () {
			var _this = this;

			//判断,如果开关没有关闭就直接进行查询,查询完毕将开关打开
			if (_this.opts.checkOldServiceMessageSwitch == 0) {
				//将查询开关关闭
				_this.opts.checkOldServiceMessageSwitch = 1;
				//上滚获取历史消息
				var page = $('.service-message-list-pack').data('page');
				_this.fetchOldMessageForService(_this.displayServiceMessageForOldMessage, '', page);
				// var param = {};
				// var serviceMessageListData = store.get($.cookie("id")+'_serviceMessageListData');
				// if(serviceMessageListData == undefined){
				//     param.id = '';
				// }else{
				//     //在数组中拿最早的一个
				//
				// }
			}
		},

		/*
     * 将客服消息设置为已读
     */
		setServiceMessageRead: function (newData, readType) {
			// console.log('准备将消息设为已读',newData);
			console.log(newData);
			if (newData.length) {
				var msgKeys = '';
				for (var i = 0; i < newData.length; i++) {
					msgKeys = msgKeys + newData[i].msgKey + ',';
					// console.log('新消息',newData[i].chatContent);
				}
				//设为已读
				msgKeys = msgKeys.substring(0, msgKeys.length - 1);
				var param = {};
				param.yyoh = $.cookie("yyoh");
				param.userId = $.cookie("id");
				param.subjectType = '1';

				// if(readType == 'getService'){
				//     param.consultMsgKeys = msgKeys;
				// }else{
				//     param.consultSendMsgKeys = msgKeys;
				// }
				var value = JSON.stringify(param);


				// treatData('pushMessage/notifyReadListToServer',value,function(data,url){
				treatData('pushMessage/notifyOneSessionHasReadToServer', value, function (data, url) {

					if (data.status.status_code == 0) {



						// console.log('设置Wie已读成功'+msgKeys);
						//判断存储中是否有存好的数据,如果与就合并数组重新存储
						var serviceMessageListData = store.get($.cookie("id") + '_serviceMessageListData');
						// console.log('旧的历史数据',serviceMessageListData);
						if (serviceMessageListData) {
							serviceMessageListData = serviceMessageListData.concat(newData);
							serviceMessageListData = array_remove_repeat(serviceMessageListData);
						}


						store.set($.cookie("id") + '_serviceMessageListData', serviceMessageListData);
						// console.log('新的历史数据',store.get($.cookie("id")+'_serviceMessageListData'));
					} else {
						alert(data.status.status_reason);
					}
				});
			}
		},

		/*
     * 获取客服一家民宿的历史聊天消息
     */
		fetchOldMessageForService: function (callbackFn, checkStatus, page) {
			hasLoadSericeNextPageData = false;
			// $('.service-message-list-wait').show();
			var _this = this;
			var param = {};
			param.yyoh = jQuery.cookie("yyoh");
			param.userId_from = jQuery.cookie("id");
			param.userId = jQuery.cookie("id");
			param.houseId = 0;
			// param.lastSendTime = '9999-99-99 00:00:00';
			param.userId_to = 0;
			var range = {};
			range.page = page || 0;
			range.pageSize = 20;
			param.range = range;
			param.subjectType = 1;
			//查询之前判断是否有历史消息在存储里,如果有就直接拿最小的
			var serviceMessageListData = store.get($.cookie("id") + '_serviceMessageListData');
			if (serviceMessageListData) {
				param.lastMessageId = serviceMessageListData[0]['id'];
			} else {
				param.lastMessageId = 0;
			}
			var value = JSON.stringify(param);
			treatData('pushMessage/fetchOldMessage', value, function (data, url) {


				// console.log(data,url);
				//查询开关打开
				_this.opts.checkOldServiceMessageSwitch = 0;
				if (data.status.status_code == 0) {
					// 增加一页
					hasLoadSericeNextPageData = true;
					// $('.service-message-list-wait').hide();
					page++;
					$('.service-message-list-pack').data('page', page);
					//如果是有历史消息
					if (data.result.MessageList.length) {
						// console.log('正式进入,存储历史数据');
						data.result.MessageList = data.result.MessageList.reverse();

						// console.log(data.result.MessageList);
						//判断存储中是否有存好的数据,如果与就合并数组重新存储
						var serviceMessageListData = store.get($.cookie("id") + '_serviceMessageListData');


						if (serviceMessageListData) {
							data.result.MessageList = data.result.MessageList.concat(serviceMessageListData);


							data.result.MessageList = array_remove_repeat(data.result.MessageList);

						}

						data.result.MessageList.sort(function (obj1,obj2) {
							return obj1.id-obj2.id;
						});

						store.set($.cookie("id") + '_serviceMessageListData', data.result.MessageList);
						//直接展示
						if (callbackFn) callbackFn(checkStatus);
					}
				}
			});
		},

		/*
        * 发布消息接口
        */
		pushOneServiceMessage: function () {
			var _this = this;
			var $serviceinputbutton = $('.service-input-button');

			var serviceMessage = $('.service-input-box-textarea').val().trim();

			if (serviceMessage.length != 0) {

				$serviceinputbutton.attr('disabled', 'disabled');


				var param = {};
				param.userId_from = jQuery.cookie("id");
				param.userId = jQuery.cookie("id");
				param.yyoh = $.cookie("yyoh");
				param.channelId = '4887233339966371802';
				param.houseId = 0;
				param.baiduId = '760580008275051542';
				param.userId_to = 0;
				// param.message = characterTransition(serviceMessage);
				param.message = serviceMessage;
				param.subjectType = 1;
				var value = JSON.stringify(param);
				var myDate = new Date();

				var month = (parseInt(myDate.getMonth()) + 1);
				month = ((month > 9) ? month : ('0' + month));
				var day = myDate.getDate();
				day = ((day > 9) ? day : ('0' + day));
				// var date = ((myDate.getHours()>9)?myDate.getHours():('0'+myDate.getHours()))+':'+((myDate.getMinutes()>9)?myDate.getMinutes():('0'+myDate.getMinutes()))+':'+((myDate.getSeconds()>9)?myDate.getSeconds():('0'+myDate.getSeconds()));
				var date = ((myDate.getHours() > 9) ? myDate.getHours() : ('0' + myDate.getHours())) + ':' + ((myDate.getMinutes() > 9) ? myDate.getMinutes() : ('0' + myDate.getMinutes()));
//             message = message.replace(new RegExp("<","g"),"&lt;");
//             message = message.replace(new RegExp(">","g"),"&gt;");
//             //现将内容写入上边的框中
//             $('#IM-TextareaContent').val('');
//             //进行发送消息
				date = month + '-' + day + ' ' + date;
				try {
					treatData('pushMessage/pushOneMessage', value, function (data, url) {
						// console.log(data,url);
						if (data.status.status_code == 0) {
							$serviceinputbutton.removeAttr('disabled');

							//放入新消息中,然其他页面渲染的时候使用
							// store.set($.cookie("id")+'_serviceMessageListNewData', data.consultMessage);
							var message = {
								chatContent: serviceMessage,
								message_key: data.result.ReturnTimeAndMsgKey.msgKey,
								messageType: 0,
								chatSendTime: date
							}
							var pushMessageItem = [{
								id: data.result.ReturnTimeAndMsgKey.messageId,
								userId_from: $.cookie("id"),
								userId_to: 0,
								message: JSON.stringify(message),
								msgKey: data.result.ReturnTimeAndMsgKey.msgKey,
								expendOnwerPush: 1,
								publish_time: data.result.ReturnTimeAndMsgKey.date
							}];
							//将自己的聊天信息也放入新消息接口中【发送消息存放处】
							// console.log('将自己的聊天信息也放入新消息接口中【发送消息存放处】');
							var serviceMessageListPushData = store.get($.cookie("id") + '_serviceMessageListPushData');
							if (serviceMessageListPushData) {
								serviceMessageListPushData = serviceMessageListPushData.concat(pushMessageItem);
								serviceMessageListPushData = array_remove_repeat(serviceMessageListPushData);
							} else {
								serviceMessageListPushData = pushMessageItem;
							}
							store.set($.cookie("id") + '_serviceMessageListPushData', serviceMessageListPushData);
							//放入历史数组中
							var serviceMessageListData = store.get($.cookie("id") + '_serviceMessageListData');
							if (serviceMessageListData) {
								var serviceMessageListData_len = serviceMessageListData.length; //发消息之前的消息长度
								serviceMessageListData = serviceMessageListData.concat(pushMessageItem);

								serviceMessageListData = array_remove_repeat(serviceMessageListData);

							} else {
								serviceMessageListData = pushMessageItem;
							}
							store.set($.cookie("id") + '_serviceMessageListData', serviceMessageListData);

							//将内容写入上边边框中
							var str = '<div class="service-message-list-prompt"></div>';
							if (serviceMessageListData_len) {
								var nowTimestamp = Date.parse(new Date()); // 现在的时间戳
								var lastMessageTimestamp = Date.parse(new Date(serviceMessageListData[serviceMessageListData_len - 1].publish_time)); // 发消息之前的最近一条消息的时间戳
								if (!lastMessageTimestamp) {
									lastMessageTimestamp = $('.service-message-list-pack .mCSB_container .service-message-list-prompt:contains("-"):last').data('stamp'); // 在页面上找到最近显示的消息时间
								}
								if (nowTimestamp - lastMessageTimestamp >= 180000) { // 两个时间戳相比，如果大于3分钟
									str = '<div class="service-message-list-prompt" data-stamp="' + nowTimestamp + '">' + date + '</div>';
								}
							}

							str = str + '<div class="service-message-item-box" id="' + data.result.ReturnTimeAndMsgKey.msgKey + '">\n\
                                    <div class="service-message-item service-right-bg">\n\
                                        <div class="service-message" iiiid>' + serviceMessage + '</div>\n\
                                        <span></span>\n\
                                    </div><div class="clear"></div>\n\
                                </div>';
							//经内容写入聊天列表中
							$('.service-message-list-pack .mCSB_container').append(str);
							//然后将滚动框滚动到最底部
							_this.messageListScrollBottom();
							//将输入框的内容清空
							$('.service-input-box-textarea').val('');
						} else {
							$serviceinputbutton.removeAttr('disabled');

                                //这里如果发送失败，就直接显示失败，用户可以重新发送
                                $('#nickName').val(data.url);
                                alert($.i18n.prop('bbfac194b8833364d3f825db714b0847'));
                            }
                        });
                    }
                    catch(e){
                        $serviceinputbutton.removeAttr('disabled');

				}

			}
		},
		/*
        * 发送关键字获取匹配问题列表
        */
		pushOneFAQTerm: function () {
			var _this = this;
			var $serviceinputbutton = $('.service-input-button');
			var serviceMessage = $('.service-input-box-textarea').val().trim();

			if (serviceMessage.length != 0) {

				$serviceinputbutton.attr('disabled', 'disabled');
				var param = {
					userId: $.cookie('id'),
					yyoh: $.cookie('yyoh'),
					query_term: serviceMessage
				};
				var value = JSON.stringify(param);
				treatData('consult/getConsultFAQAnswerByTerm',value,function(data){
					if(data.status.status_code == 0){
						//将输入框的内容清空
						_this.getMessageList('','','',function (d) {
							$('.service-input-box-textarea').val('');
							if(!data.result.faqs.length || data.result.faqs.length==0){
								$('.service-message-list-pack .mCSB_container').append('<div class="service-message-item-box">' +
									'   <div class="service-message-item-prompt">' +
									'       <div class="service-message">没有找到您想要的答案，可转<span class="color_ff6766 cursor_po openOnlineService">人工客服</span></div>' +
									'   </div>' +
									'   <div class="clear"></div>' +
									'</div>');
								_this.messageListScrollBottom();
							}else{
								_this.displayConsultFAQ(data);
							}
						});
					}else{
						alert('发送失败了');
					}
					$serviceinputbutton.removeAttr('disabled');
				});
			}
		},


		//聊天页面滚动到最底部
		messageListScrollBottom: function () {
			$('.service-message-list-pack').mCustomScrollbar("scrollTo", "bottom", {timeout: 200});
		},


		/*
     * 点击展示客服窗口
     */
		onClickServiceBox: function () {
			var _this = this;
			$('.IM-BtnMouse-Msg.im_S,.close-service-box').on('click', function (e) {

				$.cookie("openedservicebox", '1', {"expires": 1, path: "/"});

				if ($('.service-box').css('display') == 'none') {
					if (jQuery.cookie("yyoh") && jQuery.cookie("id")) {
						//发送给服务端通知,告诉我打开客服窗口了
						_this.addFirstConsultMessage();
						store.set('serviceMessageBoxIsShow', 1);
						//打开客服窗口,然后查看历史消息
						$('.service-box').show();
						$('.im_L.im_new_L.im_new_S.im_new_hover').addClass('open');
						//页面滚动到底部
						_this.messageListScrollBottom();
						//打开的时候,将service-message-item-close 最后一条设为展示,中间那个展示的隐藏
						// $('.aboveIsHistory').removeClass('aboveIsHistory');
						// $('.service-message-item-close:last').addClass('aboveIsHistory');
					} else {
						var history = window.location.pathname + window.location.search;
						history = history.length ? ('?history=' + history) : '';
						window.location.href = "/login/p_login" + history;
					}
				} else {
					store.set('serviceMessageBoxIsShow', 0);
					$('.service-box').hide();
					$('.im_L.im_new_L.im_new_S.im_new_hover').removeClass('open');
				}

			})

		},

		/*
    * 点击展示通知和看看窗口
    */
		onClickNotifyBox: function () {
			var _this = this;

			$('.IM-BtnMouse-Msg.im_new_notify,.close-look-notify-box').on('click', function (e) {
				if ($('.look-notify-items-box').css('display') == 'none') {
					if (jQuery.cookie("yyoh") && jQuery.cookie("id")) {
						// 这块初始化没有和.content一起使用使用宁为一起使用会有问题 所以不用再html里面 加类名mCustomScrollbar
						// 初始化滚动条 看看
						$('.look-items-box').mCustomScrollbar({
							mouseWheel: {preventDefault: true},
							callbacks: {
								onTotalScroll: function (event) {
									if (hasLoadLookNextPageData) {
										_this.getShowMessFun();
									}

								}
							}
						});
						// 初始化滚动条 通知
						$('.notify-items-box').mCustomScrollbar({
							mouseWheel: {preventDefault: true},
							callbacks: {
								onTotalScroll: function (event) {
									if (hasLoadnotifyNextPageData) {
										_this.getNotifyMessFun();
									}
								}
							}
						});

						$('.look-notify-items-box').show();
						$('.look-collect-box').hide();
						$('.look-feedback-box').hide();
						$('#messlist-box').hide();
						$('.im_L.im_new_L.im_new_hover.im_close').removeClass('open');
						$('.im_L.im_new_L.im_new_notify.im_new_hover').addClass('open');
						// 打开弹窗先请求数据 看看
						// $('.notify-btn').addClass('now');
						// $('.look-btn').addClass('now').siblings('.notify-btn').removeClass('now');
						$('.notify-items-box').show();
						$('.look-notify-no-item').hide();
						$('.look-items-box').hide();
                        $('.notify-items-box .mCSB_container').html('');
                        $('.notify-items-box').data('page', '0');
                        _this.getNotifyMessFun();
						// $('.look-items-box').data('page', '0');
						// _this.getShowMessFun();
						//打开窗口,然后查看历史消息
						$('.look-notify-items-box').show();
						// 点击看看
						$('.look-btn').click(function () {
							$(this).addClass('now').siblings('.notify-btn').removeClass('now');
							$('.notify-items-box').hide();
							$('.look-notify-no-item').hide();
							$('.look-items-box').show();
							$('.look-items-box .mCSB_container').html('');
							$('.look-items-box').data('page', '0');
							_this.getShowMessFun();

						});
						// 点击通知
						$('.notify-btn').click(function () {
							// $(this).addClass('now').siblings('.look-btn').removeClass('now');
							$('.notify-items-box').show();
							$('.look-notify-no-item').hide();
							$('.look-items-box').hide();
							$('.notify-items-box .mCSB_container').html('');
							$('.notify-items-box').data('page', '0');
							_this.getNotifyMessFun();
						});
					} else {
						var history = window.location.pathname + window.location.search;
						history = history.length ? ('?history=' + history) : '';
						window.location.href = "/login/p_login" + history;
					}
				} else {
					$('.look-notify-items-box').hide();
					$('.im_L.im_new_L.im_new_notify.im_new_hover').removeClass('open');
				}

			});


		},
		/*
    * 点击展示 我的收藏 窗口
    */
		onClickCollectBox: function () {
			var _this = this;
			$('.IM-BtnMouse-Msg.im_new_collect,.close-collect-box').on('click', function (e) {

				if ($('.look-collect-box').css('display') == 'none') {
					if (jQuery.cookie("yyoh") && jQuery.cookie("id")) {
						// 滚动到底部加载新一页数据
						$('.collect-items-box').mCustomScrollbar({
							mouseWheel: {preventDefault: true},
							callbacks: {
								onTotalScroll: function (event) {
									if (hasLoadCollectNextPageData) {
										_this.getCollectMessFun();
									}

								}
							}
						});

						$('.look-notify-items-box').hide();
						$('.look-collect-box').show();
						$('.look-feedback-box').hide();
						$('#messlist-box').hide();
						$('.im_L.im_new_L.im_new_hover.im_close').removeClass('open');
						$('.im_L.im_new_L.im_new_collect.im_new_hover').addClass('open');
						$('.collect-items-box').data('page', '0');
						_this.getCollectMessFun();
						//打开,然后查看历史消息
						$('.look-collect-box').show();
					} else {
						var history = window.location.pathname + window.location.search;
						history = history.length ? ('?history=' + history) : '';
						window.location.href = "/login/p_login" + history;
					}
				} else {

					$('.im_L.im_new_L.im_new_collect.im_new_hover').removeClass('open');
					$('.look-collect-box').hide();
				}

			})

		},
		/*
    * 点击展示 意见反馈 窗口
    */
		onClickfeedbackBox: function () {
			var _this = this;
			$('.IM-BtnMouse-Msg.im_new_feedback,.close-feedback').on('click', function (e) {
				if ($('.look-feedback-box').css('display') == 'none') {
					if (jQuery.cookie("yyoh") && jQuery.cookie("id")) {
						$('.look-notify-items-box').hide();
						$('.look-collect-box').hide();
						$('#messlist-box').hide();
						$('.look-feedback-box').show();
						$('.im_L.im_new_L.im_close').removeClass('open');
						$('.im_L.im_new_L.im_new_feedback.im_new_hover').addClass('open');

						$('.feedback-input-box').show(); // 重新打开无论上次编辑是否完成，都应该在填写信息页面
						$('.feedback-success-box').hide();
						_this.setFeedbackMessFun();
						//打开客服窗口,然后查看历史消息
						$('.look-feedback-box').show();

						//页面滚动到底部
						_this.messageListScrollBottom();

					} else {
						var history = window.location.pathname + window.location.search;
						history = history.length ? ('?history=' + history) : '';
						window.location.href = "/login/p_login" + history;
					}
				} else {
					$('.look-feedback-box').hide();
					$('.im_L.im_new_L.im_new_feedback.im_new_hover').removeClass('open');
				}

			})
		},

   /**
    * 获取看看的信息内容
    */
   getShowMessFun: function() {
       hasLoadLookNextPageData = false;
       var _this = this;
       if(parseInt($('#lookBtnNum').html()) > 0) {
           var type = 2;
           _this.setLookNotifyMessFun(type);
       }
       console.log(this)
       var param = {};
       param.yyoh = jQuery.cookie("yyoh");
       param.userId = jQuery.cookie("id");
       var range = {};
       var page = $('.look-items-box').data('page');
       var divId = $('.look-items-box>div').attr('id');
       console.log(page);
       range.page = page;
       range.pageSize = 10;
       param.range = range;
       param.type = '1';
       var value = JSON.stringify(param);
       treatData('pushMessage/getSessionHistoryList',value,function(data) {
           console.log(data);
           if(data.status.status_code == 0) {
               hasLoadLookNextPageData = true;
               if(data.result.total == 0) {
                   $('.notify-items-box').hide();
                   $('.look-items-box').hide();
                   $('.look-notify-no-item').show();
                   $('.look-notify-list-no-item-tips').html($.i18n.prop('c1aa60763a2d8e1ab2c5b5bdd4617231'));
               } else if(!data.result.list && !data.result.list.length) {
                   // 没有看看显示无看看空白页
                   $('.look-items-box .mCSB_container').mCustomScrollbar({mouseWheel:{ preventDefault:true },callbacks:{ onTotalScroll:function(){
                       // alert('1111')
                   } }});
                    return false;

               } else {
                   var str = '';
                   for(var i=0;i<data.result.list.length;i++) {
                       str += '<div class="look-notify-list-item"><div class="look-notify-list-item-title">';
                       str += '<img class="look-notify-img " src="'+data.result.list[i].iconUrl+'" alt="">';
                       str += '<span class="look-notify-detail ">';
                       str += '<span class="fl look-notify-detail-name">'+data.result.list[i].title+'</span>';
                       str += '<span class="fr look-notify-detail-time">'+data.result.list[i].createdAt.split(' ')[0]+'</span></span>';
                       str += '<div class="clear"></div></div>';
                       str += '<div class="look-notify-list-item-mess">'+data.result.list[i].summary+'</div>';
                       str += '<div class="look-notify-list-item-img">';
                       str += '<img class="" src="'+data.result.list[i].mainPictureUrl+'" onerror="onImgErr()" alt=""></div>';
                       str += '<a target="_blank" href="'+data.result.list[i].jumpUrl;
                       str += '" class="look-notify-item-more">' +$.i18n.prop('1f873be4c735fd5af9a210e1527bc522') + '</a></div>';
                   }

						if ($('.look-items-box').data('page') == 0) {
							// $('.look-items-box #'+divId+'_container').html(str);
							$('.look-items-box .mCSB_container').html(str);
						} else {
							// $('.look-items-box #'+divId+'_container').append(str);
							$('.look-items-box .mCSB_container').append(str);
						}
						// $(".look-items-box").mCustomScrollbar("update");
						// 下拉加载改变请求页数
						$('.look-items-box').data('page', $('.look-items-box').data('page') - (-1));
						// 滚动到底部加载新一页数据
						// $('.look-items-box #'+divId).mCustomScrollbar({mouseWheel:{ preventDefault:true },callbacks:{ onTotalScroll:function(){
						//
						//     _this.getShowMessFun();
						// } }});

					}


				}

			});
		},
		/**
		 * 获取通知的信息内容
		 */
		getNotifyMessFun: function () {
			hasLoadnotifyNextPageData = false;
			var _this = this;
			if (parseInt($('#notifyBtnNum').html()) > 0) {
				var type = 1;
				_this.setLookNotifyMessFun(type);
			}

       var param = {};
       param.yyoh = jQuery.cookie("yyoh");
       param.userId = jQuery.cookie("id");
       var range = {};
       var page = $('.notify-items-box').data('page');
       var divId = $('.notify-items-box>div').attr('id');
       range.page = page;
       range.pageSize = 10;
       param.range = range;
       param.type = '2';
       var value = JSON.stringify(param);
       treatData('pushMessage/getSessionHistoryList',value,function(data) {
           console.log(data);
           if(data.status.status_code == 0) {
               console.log(data.result.list.length);
               hasLoadnotifyNextPageData = true;
               if(data.result.total == 0 || data.result.list.length == 0) {
                   // 没有通知显示无通知空白页
                   $('.notify-items-box').hide();
                   $('.look-items-box').hide();
                   $('.look-notify-no-item').show();
                   $('.look-notify-list-no-item-tips').html($.i18n.prop('714995c80ce6d9ca12eaa06352f5ef9e'));
               } else if(!data.result.list && !data.result.list.length) {
                   $('.notify-items-box .mCSB_container').mCustomScrollbar({mouseWheel:{ preventDefault:true },callbacks:{ onTotalScroll:function(){
                       // alert('1111')
                   } }});
                    return false;
               } else {
                   var str = '';
                   for(var i=0;i<data.result.list.length;i++) {
                       str += '<div class="look-notify-list-item"><div class="look-notify-list-item-title">';
                       str += '<img class="look-notify-img " src="/images/feedback/index-notify-tips.png" alt="">';
                       str += '<span class="look-notify-detail ">';
                       str += '<span class="fl look-notify-detail-name">' + $.i18n.prop('b772f7f9b8a518e8f167668a09441790') + '</span>';
                       str += '<span class="fr look-notify-detail-time">'+data.result.list[i].publish_time.split(' ')[0]+'</span></span>';
                       str += '<div class="clear"></div></div>';
                       str += '<div class="look-notify-list-item-mess">'+JSON.parse(data.result.list[i].message).chatContent+'</div>';
                       // str += '<a href="" class="look-notify-item-more">查看详情>></a></div>';
                       str += '</div>';
                   }
                   if($('.notify-items-box').data('page') == 0) {
                       $('.notify-items-box .mCSB_container').html(str);
                   } else {
                       $('.notify-items-box .mCSB_container').append(str);
                   }
                   // 如果有通知里面有链接就加一个a点击可以跳转
                   var urlDom = $('.skipUrl');
                   if(urlDom.length) {
                       for(var i=0;i<urlDom.length;i++){
                           var url = $(urlDom[i]).data('url');
                           var html = $(urlDom[i]).html();
                           var str = '<a style="color: #333;" href="'+url+'" target="_blank">'+html+'</a>';
                           $(urlDom[i]).html(str);
                       }
                   }
                   // 下拉加载改变请求页数
                   $('.notify-items-box').data('page',$('.notify-items-box').data('page')-(-1));
                   // // 滚动到底部加载新一页数据
                   // $('.notify-items-box .mCSB_container').mCustomScrollbar({mouseWheel:{ preventDefault:true },callbacks:{ onTotalScroll:function(){
                   //
                   //     _this.getNotifyMessFun();
                   // } }});
               }
           }

			});
		},

		/**
		 * 将通知和看看诶未读消息设置为已读
		 * type 1:标记通知已读,2:标记看看已读
		 */
		setLookNotifyMessFun: function (type) {
			var _this = this;
			var param = {};
			param.yyoh = jQuery.cookie("yyoh");
			param.userId = jQuery.cookie("id");
			param.type = type;
			var value = JSON.stringify(param);
			treatData('pushMessage/markMyNotificationAllRead', value, function (data) {
				console.log(data);
				if (data.status.status_code == 0) {

					if (type == 1) {
						$('#notifyBtnNum').hide().html('');
					} else {
						$('#lookBtnNum').hide().html('');
					}
				}

			});
		},
		/**
		 * 获取 我的收藏 的信息内容
		 */
		getCollectMessFun: function () {
			hasLoadCollectNextPageData = false;
			var _this = this;
			var param = {};
			param.yyoh = jQuery.cookie("yyoh");
			param.userId = jQuery.cookie("id");
			var range = {};
			var page = $('.collect-items-box').data('page');
			var divId = $('.collect-items-box>div').attr('id');
			console.log(page);
			range.page = page;
			range.pageSize = 10;
			param.range = range;
			var value = JSON.stringify(param);
			treatData('collect/getCollectListByUserId', value, function (data) {
				console.log(data);
				if (data.status.status_code == 0) {  // data.result.houseList.total == 0 &&
					hasLoadCollectNextPageData = true;
					if (range.page == 0 && data.result.houseList == "[]") {
						// 没有收藏显示无收藏空白页
						$('.collect-no-list-box').show();
						$('.collect-items-box').hide();
						return false;
					} else if (!data.result.houseList.length || (range.page != 0 && data.result.houseList == "[]")) {
						$('.collect-items-box').mCustomScrollbar({
							mouseWheel: {preventDefault: true}, callbacks: {
								onTotalScroll: function () {
									// alert('1111')
								}
							}
						});
						return false;

               } else {
                   $('.collect-no-list-box').hide();
                   var str = '';
                   for(var i=0;i<data.result.houseList.length;i++) {
                       var levelName = (data.result.houseList[i].levelName3 && data.result.houseList[i].levelName3 != $.i18n.prop('f5a7f30e1878cd0b13bde467d4f8d713'))?data.result.houseList[i].levelName3:((data.result.houseList[i].levelName2 && data.result.houseList[i].levelName2!=$.i18n.prop('f5a7f30e1878cd0b13bde467d4f8d713'))?data.result.houseList[i].levelName2:((data.result.houseList[i].levelName1 && data.result.houseList[i].levelName1!=$.i18n.prop('f5a7f30e1878cd0b13bde467d4f8d713'))? data.result.houseList[i].levelName1: $.i18n.prop('f5a7f30e1878cd0b13bde467d4f8d713')))
                       var roomType = data.result.houseList[i].roomType == 1 ? $.i18n.prop('783ee50901b8cec7b99e1d158ab865bc') : (data.result.houseList[i].roomType == 2 ? $.i18n.prop('c29e4208c24cc4c395d3095e1e9fab8b') :$.i18n.prop('0fec9b9aac51aa08407823521a4c0f6a'))
                       var imgSrc = '/images/pic_default_image.png'
                       str += '<a target="_blank" href="/h/'+data.result.houseList[i].id+'"><div class="collect-list-item">';
                       str += '<img class="collect-list-item-img fl" src="'+data.result.houseList[i].mainPictureUrl+'" onerror="onImgErr()" alt="">';
                       str += '<div class="collect-list-item-detail fr">';
                       str += '<p class="collect-list-item-detail-title">'+data.result.houseList[i].title+'</p>';
                       str += '<p class="collect-list-item-detail-des">';
                       str += $.i18n.prop('46fa239ca05fd922eb039f47a0915cbb')+levelName+'</p>';
                       str += '<p class="collect-list-item-detail-other">'+roomType+'-'+data.result.houseList[i].accommodateNum+$.i18n.prop('4c665ec45d9d6e4567e5334a81cb21fd')+data.result.houseList[i].bedroomNum+$.i18n.prop('801546f5085e6b0d5b874f00e577bb01')+data.result.houseList[i].bedNum+$.i18n.prop('86cda3c7696069771fdcbffcf5c47ce8') + '</p></div>';
                       str += '<div class="clear"></div></div></a>';

						}

						if ($('.collect-items-box').data('page') == 0) {
							$('.collect-items-box  .mCSB_container').html(str);
						} else {
							$('.collect-items-box .mCSB_container').append(str);
						}
						// 下拉加载改变请求页数
						$('.collect-items-box').data('page', $('.collect-items-box').data('page') - (-1));


					}


				}

       });
   },
    /**
    * 提交 意见反馈 的信息内容
    */
   setFeedbackMessFun: function() {
        $(".feedback-button").click(function(){
            var $this = $(this);
            // $this.attr('disabled','disabled');
            //判断是否为空
            var userFeedback = $("#feedback-text").val();
            var contactInfo = $("#feedback-contact").val();
            var reg = /^\s*$/g;
            if(userFeedback == '' || reg.test(userFeedback)){
                $(".feedback-error").html($.i18n.prop('976a879a1c18e92b623fc860c7125536'));
                return;
            }
            var param = {
                yyoh: jQuery.cookie('yyoh'),
                userId: jQuery.cookie('id'),
                userFeedback:userFeedback,
                contactInfo:contactInfo

				};
				var value = JSON.stringify(param);
				treatData('feedback/addFeedback', value, function (data, url) {
					console.log(data, url);
					if (data.status.status_code == 0) {
						$('.feedback-input-box').hide();
						$('.feedback-success-box').show();
						$('.feedback-mess').val('');
						$('.feedback-contact').val('');
					} else {
						alert(data.status.status_reason)
					}

				});
			});


			$('.close-feedback-to-pre').click(function () {
				$('.feedback-input-box').show();
				$('.feedback-success-box').hide();
			});

   },
   // 关闭聊天空白弹窗
   onNoSessionListBtn: function() {
      $('.close-messlist-box, .im_new_notify, .im_new_collect, .im_new_feedback').click(function() {
          $('#messlist-box').hide();
          $('.im_L.im_M.im_new_L.im_new_M.im_new_hover').removeClass('open');
          // jQuery.cookie("chatwin_overflow",'hidden',{path:"/"});
      })
   },


		/*
     * 直接渲染信息当有新的消息过来的时候【渲染所有新的消息】
     */
		displayServiceMessageOnGetNewMessage: function () {

			var _this = this;
			//渲染其他段发来的新消息
			var serviceMessageListNewData = store.get($.cookie("id") + '_serviceMessageListNewData');
			// console.log('serviceMessageListNewData',serviceMessageListNewData);
			if (serviceMessageListNewData && serviceMessageListNewData.length) {

				var inTag = 0;

				var $servicelistpack = $('.service-message-list-pack .mCSB_container');

				for (var i = 0; i < serviceMessageListNewData.length; i++) {
					var str = _this.displayServiceMessageForStr(serviceMessageListNewData[i]);
					if (str == '') continue;
					var message = JSON.parse(serviceMessageListNewData[i].message);
					var msgKeys = msgKeys + message.message_key + ',';
					if ($('#' + message.message_key).length == 0) {
						inTag++;


						var $lastchild = $servicelistpack.find('.service-message-item-box:last');
						if ($lastchild.length > 0) {//原本有数据
							var datasortid = $lastchild.attr('datasortid');

							if (datasortid && datasortid < serviceMessageListNewData[i].id) { //防止顺序错乱
								//经内容写入聊天列表中
								$servicelistpack.append(str);
							} else if (datasortid > serviceMessageListNewData[i].id) {//id小的反而在后面,则不再追加,而是插入到指定的位置

								var $itemboxlist = $servicelistpack.find('.service-message-item-box');
								for (var k = $itemboxlist.length - 1; k >= 0; k--) {

									var $tempitem = $itemboxlist.eq(k);
									var tempid = $tempitem.attr('datasortid');
									if (tempid > serviceMessageListNewData[i].id) {
										$tempitem.before($(str));

										break;
									}
								}
							} else if (!datasortid) {
								$servicelistpack.append(str);
							}
						} else {
							$servicelistpack.append(str);
						}


					} else {
						// console.log('有重复,抛弃');
					}
				}
				if (inTag) {
					//然后将滚动框滚动到最底部
					// console.log('来了新消息---然后将滚动框滚动到最底部');
					_this.messageListScrollBottom();
				}

			}

			var serviceMessageListPushData = store.get($.cookie("id") + '_serviceMessageListPushData')
			if (serviceMessageListPushData) {
				// console.log('渲染发送出去的消息');
				var inTag = 0;
				for (var i = 0; i < serviceMessageListPushData.length; i++) {
					var str = _this.displayServiceMessageForStr(serviceMessageListPushData[i]);
					if (str == '') return;
					try {
						var message = JSON.parse(serviceMessageListPushData[i].message);
						if ($('#' + message.message_key).length == 0) {
							inTag++;
							//将内容写入聊天列表中
							$('.service-message-list-pack .mCSB_container').append(str);
						} else {
							// console.log('发送出去的消息有重复,抛弃');
						}


					} catch (e) {
					}


				}
				if (inTag) {
					//然后将滚动框滚动到最底部
					// console.log('同步的其他页面的消息---然后将滚动框滚动到最底部');
					_this.messageListScrollBottom();
				}
			}


			var $servicebox = $('.service-box');
			if ($servicebox.attr('setnewpos') == '1') {
				$servicebox.removeAttr('setnewpos');
				var $abovehistory = $servicebox.find('.service-message-item-close');
				$abovehistory.removeClass('aboveIsHistory');
				$abovehistory.filter(':last').addClass('aboveIsHistory');

			}
		},

		/*
     * 进入页面的的时候就直接查询存储器中的消息,然后直接渲染到页面中,并且查看是否展示聊天窗口
     */
		displayServiceMessageOnPageInit: function () {

			var _this = this;
			//如果存储中的是1,就直接打开窗口
			var serviceMessageBoxIsShow = store.get('serviceMessageBoxIsShow');
			if (serviceMessageBoxIsShow == 1) {
				$('.service-box').show();
				$('.im_L.im_new_L.im_new_S.im_new_hover').addClass('open');
				_this.messageListScrollBottom();//聊天页面滚动到最底部
			}
			_this.fetchOldMessageForService(function (checkStatus) {
				_this.displayServiceMessageForOldMessage(checkStatus);
				//发送常见问题列表
				_this.getConsultFAQ();
			}, 'pageinit');//获取客服一家民宿的历史聊天消息

		},

		/*
     * 发送给服务端通知,告诉我打开客服窗口了
     */
		addFirstConsultMessage: function () {
			//通知服务器我进来了
			// console.log('通知服务器我进来了');
			var param = {};
			param.userId_from = jQuery.cookie("id");
			param.userId = jQuery.cookie("id");
			param.yyoh = $.cookie("yyoh");
			param.channelId = '4887233339966371802';
			param.houseId = 0;
			param.baiduId = '760580008275051542';
			param.userId_to = 0;
			param.message = '';
			param.messageType = 0;
			var value = JSON.stringify(param);
			treatData('pushMessage/addFirstConsultMessage', value, function (data, url) {
				// console.log('通知服务器我进来了',data,url);

				if (data.status.status_code == 0) {//修改servicebox的历史记录位置属性
					$('.service-box').attr('setnewpos', '1');
				}
			});
		},

		/*
     * 进入页面的时候通过displayServiceMessageOnPageInit方法查询消息,通过此方法渲染消息【渲染所有历史消息】
     */
		displayServiceMessageForOldMessage: function (checkStatus) {
			try {
				var _this = this;
				var serviceMessageListData = store.get($.cookie("id") + '_serviceMessageListData');
				if (serviceMessageListData) {
					//将数组反序
					serviceMessageListData = serviceMessageListData.reverse();
					//去掉等待图标
					$('.service-message-list-wait').remove();


					var flag = 0;

					//渲染历史消息
					for (var i = 0; i < serviceMessageListData.length; i++) {
						var str = _this.displayServiceMessageForStr(serviceMessageListData[i]);

						if (str == '') continue;
						var message = JSON.parse(serviceMessageListData[i].message);
						if ($('#' + message.message_key).length == 0) {
							flag++;


							//经内容写入聊天列表中
							$('.service-message-list-pack .mCSB_container').prepend(str);
						} else {
							// console.log('有重复,抛弃');
						}
					}

					var $servicebox = $('.service-box');
					if ($servicebox.attr('setnewpos') == '1') {

						$servicebox.removeAttr('setnewpos');
						var $abovehistory = $servicebox.find('.service-message-item-close');
						$abovehistory.removeClass('aboveIsHistory');
						$abovehistory.filter(':last').addClass('aboveIsHistory');

					}

					//然后将滚动框滚动到最底部
					if (checkStatus == 'pageinit') {//页面初始化

						_this.messageListScrollBottom();
					} else {
						// $('.service-message-list-pack').mCustomScrollbar("scrollTo","200");
					}


				}
			}
			catch (e) {
			}

		},


		/*
     * 客服俩天信息渲染的时候的一个内容字符串拼接
     */
		displayServiceMessageForStr: function (data) {
			try {
				var str = '', styleR = '';
				var message = null;
				try {
					message = JSON.parse(data.message);
				}
				catch (e) {
				}
				if (data.userId_from == $.cookie('id')) {
					styleR = 'service-right-bg';
				}
				if (message.messageType == 3 || message.messageType == 4) {

					if (data.userId_from != $.cookie('id')) {//服务器代客户发的消息要丢掉
						var tagMessage = '';
						if (message.messageType == 4) {



                         if($('.aboveIsHistory').length>0){
                             //证明是历史消息标记
                             tagMessage = 'service-message-item-close';
                             message.chatContent = $.i18n.prop('e505d3b41e5dfe8a2896efb4088574ad');
                         }else{
                             tagMessage = 'service-message-item-close aboveIsHistory';
                             message.chatContent = $.i18n.prop('e505d3b41e5dfe8a2896efb4088574ad');
                         }
                     }


						str = '<div class="service-message-item-box ' + tagMessage + '" id="' + message.message_key + '">' +
							'<div class="service-message-item-prompt">' +
							'<span class="service-message">' + message.chatContent + '</span>' +
							'</div>' +
							'<div class="clear"></div>' +
							'</div>';


					}

				} else {
					if (message.messageType == 2) {
						var img = publicMethods.getHouseUrl(message.chatContent, 'large', 100, true)
						message.chatContent = '<img class="pic mCS_img_loaded" src="' + img + '">';
						styleR = styleR + ' message_pic';
					}


					var lastStamp = $('.service-message-list-pack .mCSB_container .service-message-list-prompt:contains("-"):last').data('stamp'); // 在页面上找到最近显示的消息时间
					var chatSandTimeShow = message.chatSendTime;
					if (lastStamp) {
						var nowStamp = Date.parse(new Date());
						if (nowStamp - lastStamp < 180000) {
							chatSandTimeShow = '';  // 如果距离现在小于3分钟，则不显示消息时间
						}
					}
					if (chatSandTimeShow.length > 15) {
						chatSandTimeShow = chatSandTimeShow.substring(5, chatSandTimeShow.length - 3);
					}

					//发送者的消息样式
					str = '<div class="service-message-list-prompt" data-stamp="' + Date.parse(message.chatSendTime) + '">' + chatSandTimeShow + '</div>' +
						'<div class="service-message-item-box" datasortid="' + data.id + '" id="' + message.message_key + '" data="' + message.messageType + '">' +
						'<div class="service-message-item ' + styleR + '">' +
						'<div class="service-message">' + message.chatContent + '</div>' +
						'<span></span>' +
						'</div>' +
						'<div class="clear"></div>' +
						'</div>';


				}
				if(message.messageType == 6){
					str += '<div class="service-message-item-box">' +
						'   <div class="service-message-item-prompt">' +
						'       <div class="service-message">不是你想要的回答？可转 <span class="color_ff6766 cursor_po openOnlineService">人工客服</span> </div>' +
						'   </div>' +
						'   <div class="clear"></div>' +
						'</div>';
				}
				return str;
			}
			catch (e) {
				console.log('----' + e);
			}

		},

		/***共享历史记录****/
		shareHistoryMessage: function () {
			var histerInterval = setInterval(function () {
				try {
					var historyten = localStorage.getItem("historyten");
					if (!historyten)
						return;

					historyten = JSON.parse(historyten);

					var $msgcontent = $('#chatcontentlistbox .msg-content:visible');
					if ($msgcontent.length == 0)
						return;

					// var currmsgcontentid=$msgcontent.attr('id');


					if ($msgcontent.attr('msgusertag') == historyten.itemid.split('msg-content-')[1]) {

						var $talktime = $msgcontent.find('.window_con .talk_time');
						if ($msgcontent.length == 0)
							return;
						//var talktimelen=Math.ceil($talktime.length/10);
						var $firstnode = $talktime.filter('.talk_time:eq(0)');
						if ($firstnode.length == 0)
							return;
						if (historyten.linkdusertoid == $firstnode.attr('id')) {//最新的历史记录,否则不加载

							if ($firstnode.attr('id') == historyten.lastchildid || $msgcontent.find('.talk_time[id=' + historyten.lastchildid + ']').length > 0)
								return;
							$msgcontent.find('.mCSB_container >div').prepend(historyten.historycontent);

							var height = (historyten.historycount * 73 - 73) + 'px';


							$msgcontent.find('.talk_con').mCustomScrollbar({setTop: height});
						}
					}
				}
				catch (e) {
					console.log(e)
				}
			}, 3000);

		},

		/**********
		 *推荐房源
		 ********/
		onInitRecommendHouse: function () {
			var _this = this;
			var page = 1;
			_this.getRoomList(page, _this.displayRecommendHouse);
			// 滚动条
			$('.recommend-content').mCustomScrollbar({
				mouseWheel: {
					preventDefault: true
				},
				callbacks: {
					// Scrolled to end of content.
					onTotalScroll: function () {
						if (!_this.opts.continueGetRoomList) {
							return;
						}
						var houseKey = $(this).val().trim();
						if (houseKey) {
							_this.getSearchRoomList(houseKey, 1, ++page, 10, _this.displayRecommendHouse);
						} else {
							_this.getRoomList(++page, _this.displayRecommendHouse);
						}
						console.log(page);
					}
				}
			});
			// 打开推荐房源窗口
			$('#IM-recommend').click(function () {
				var top = $('#IM-Chatwin').css('top'),
					left = Number($('#IM-Chatwin').css('left').split('px')[0]),
					chatWidth = $('#IM-Chatwin').width(),
					recommendWith = $('.recommend-house').width();
				// 如果右边无法显示推荐房源窗口的一半以上则放聊天窗口的左边
				if ($(window).width() - left - chatWidth - 100 < recommendWith) {
					$('.recommend-house').css({
						'top': top,
						'left': $(window).width() - recommendWith - 80 + 'px',
						'z-index': $('#IM-Chatwin').css('z-index')
					});
				} else {
					$('.recommend-house').css({
						'top': top,
						'left': left + chatWidth + 100 + 'px',
						'z-index': $('#IM-Chatwin').css('z-index')
					});
				}

				$('.recommend-house').show();

			});
			// 关闭
			$('.recommend-close').click(function () {
				$('.recommend-house').hide();
			});
			// 拖动
			try {
				$('#recommend-house').draggable({
					stack: '#IM-Chatwin,.service-box,#recommend-house', // 当停止拖拽时，最后一个被拖拽的项目总是出现在同组其他项目的上面
					snap: '#IM-Chatwin',
					snapMode: 'outer', // 可以对齐到聊天窗口外部
					addClasses: false,//禁止加载jquery ui样式,没有用到jquery ui原本的样式,防止可提升效率
					containment: 'body',//只在文档内拖动
					scroll: false,
					opacity: 0.98,//拖动时聊天框的不透明度
					cursor: 'move',
					handle: '.recommend-title',//可拖动的元素
					stop: function (event, ui) {//拖动成功,释放鼠标时触发

					}
				});
			} catch (e) {

			}
			// 搜索房源
			$('.recommend-house [name=house-search-input]').bind('input propertychange', function () {
				// 初始化
				page = 1;
				_this.opts.continueGetRoomList = true;

				var houseKey = $(this).val().trim().replace('\'', '');
				setTimeout(function () {
					if (houseKey) {
						_this.getSearchRoomList(houseKey, 1, page, 10, _this.displayRecommendHouse);
					} else {
						_this.getRoomList(page, _this.displayRecommendHouse);
					}
				}, 500);

				$('.recommend-content').mCustomScrollbar('scrollTo', 'top'); // 滚动到顶部

           })
       },
       // 推荐房源获取房源列表
       getRoomList: function (page, fn) {
           var _this = this;
           var typeNum = '1';
           if($.cookie("buyer_currency")){
               typeNum = $.cookie("buyer_currency");
           }
           var param = {};
           param.yyoh = $.cookie('yyoh');
           param.userId = $.cookie('id');
           var range = {};
           range.pageSize = 10;
           range.page = page - 1;
           param.range = range;
           param.isCurrency = 1;
           param.typeNum = typeNum;
           var value = JSON.stringify(param);
           treatData('house/getHouseListByUserId', value, function (data, url) {
               if(data.result.houseCount == 0){
                   // 不是房东，没有推荐房源功能
                   $('#IM-recommend').hide();
               }else{
                   $('#IM-recommend').show();
                   // 不用滚动分页了
                   if(data.result.houseList.length < 10 || JSON.stringify(data.result.houseList) == '{}'){
                       _this.opts.continueGetRoomList = false;
                   }
                   if (fn) {
                       fn(data,range,'list');
                   }
               }
           }, function () {
               var status = {};
               status.status_code = -1;
               status.status_reason = $.i18n.prop('a9b5ce23ede1a038a3c65fb3a0817699');
               var data = {status: status};
               if (fn) {
                   fn(data);
               }
           });
       },
       // 推荐房源搜索
	   getSearchRoomList: function(houseKey,onLineHouse,page,pageSize,fn){
		   var _this = this;
		   var param = {};
		   param.yyoh = $.cookie('yyoh');
		   param.userId = $.cookie('id');
		   var range = {};
		   range.pageSize = pageSize;
		   range.page = page - 1;
		   param.range = range;
		   param.keyWord = houseKey;
		   param.onLineHouse = onLineHouse;
		   param.typeNum = $.cookie('buyer_currency') || 1;
		   param.attrList = ['*'];
		   var value = JSON.stringify(param);
		   treatData('house/searchMyHouse',value,function(data,url){
			   // 不用滚动分页了
			   if(data.result.houseList.length < 10 || JSON.stringify(data.result.houseList) == '{}'){
				   _this.opts.continueGetRoomList = false;
			   }
			   if(fn){
				   fn(data,range,'search');
			   }
		   },function(){
			   var status = {};
			   status.status_code = -1;
			   status.status_reason = $.i18n.prop('a9b5ce23ede1a038a3c65fb3a0817699');
			   if(fn){
				   fn(status);
			   }
		   });
       },
       // 推荐房源展示房源列表
       displayRecommendHouse: function (data,range,type) {
           if (data.status.status_code == 0) {
               if (data.result.houseCount == 0 || data.result.num == 0) {
                   $('.recommend-empty').show();
                   if (type == 'search') {
                       $('.recommend-empty .searchResult').show();
                       $('.recommend-empty .listResult').hide();
                   } else {
                       $('.recommend-empty .listResult').show();
                       $('.recommend-empty .searchResult').hide();
                   }
                   $('.recommend-content').hide();
               } else {
                   $('.recommend-empty').hide();
                   $('.recommend-content').show();
                   var houseList = data.result.houseList;
                   var currency_symbol_arr = JSON.parse($.cookie("currency_symbol_arr"));
                   var roomType = [$.i18n.prop('171233d86cf4b71268ec4b8048f69a20'), $.i18n.prop('82cf9d8d68b82584ecc68bf4fed0639c'), $.i18n.prop('77f5873a3ae1bfa3c4f5e049e6a01d71'), $.i18n.prop('7219ffbfc3b2b4f91bf627237a771ac7')];
                   var str = '';
                   for (var i = 0; i < houseList.length; i++) {
                       var currency_symbol = currency_symbol_arr[houseList[i].currency - 1].symbol || '';
                       str += '<li houseid="' + houseList[i].id + '" title="' + houseList[i].title + '" currency="' + houseList[i].currency + '" price="' + (houseList[i].houseCalendarPrice ? houseList[i].houseCalendarPrice : houseList[i].pricePerNight) + '" ' +
                           'picture="' + houseList[i].mainPictureUrl + '" roomtype="' + houseList[i].roomType + '" accommodatenum="' + houseList[i].accommodateNum + '">\n' +
                           '            <a href="/h/' + houseList[i].id + '" target="_blank"><img class="house-img" src="' + houseList[i].mainPictureUrl + '"/></a>\n' +
                           '            <div class="house-info">\n' +
                           '                <a href="/h/' + houseList[i].id + '" target="_blank"><p class="house-info-title">' + houseList[i].title + '</p></a>\n' +
                           '                <p class="house-info-feature">' + roomType[houseList[i].roomType] + '-' + houseList[i].accommodateNum + $.i18n.prop('4c665ec45d9d6e4567e5334a81cb21fd') + houseList[i].bedroomNum + $.i18n.prop('e603bdcd2db78a07509c4318358c3d03') + '</p>\n' +
                           '                <p class="house-info-price">' + currency_symbol + Math.round(houseList[i].houseCalendarPrice ? houseList[i].houseCalendarPrice : houseList[i].pricePerNight) + '</p>\n' +
                           '            </div>\n' +
                           '            <span class="recommend-btn">' +
                           $.i18n.prop('7de8848a4c4e64905e69e81f2ee6c88e') +
                           '</span></li>';
                   }
                   if (range.page == 0) {
                       $('.recommend-content .mCustomScrollBox .mCSB_container').html(str);
                   } else {
                       $('.recommend-content .mCustomScrollBox .mCSB_container').append(str);
                   }
               }
           } else {
               alert(data.status.status_reason);
           }
       },

	   //获取常见问题列表
	   getConsultFAQ: function () {
		   var _this = this;
		   var param = {
			   yyoh: $.cookie('yyoh'),
			   userId: $.cookie('id')
		   };
		   var value = JSON.stringify(param);
		   treatData('consult/getConsultFAQ', value, function (data) {
			   if (data.status.status_code == 0) {
				   _this.displayConsultFAQ(data);
			   } else {
				   alert(data.status.status_reason)
			   }
		   })
	   },
		displayConsultFAQ: function(data){
               var _this = this;
               var date = new Date();
               var chatSandTimeShow = getNowTime().substring(5, 16);

               var consultListStr = '';
			var faqs = data.result.faqs;
			for(var i = 0; i < faqs.length; i++) {
				consultListStr += '<p class="faqItem" data-id="' + faqs[i].id + '">' + (i + 1) + '. ' + faqs[i].question + '</p>';
			}

			var str = '<div class="service-message-list-prompt" data-stamp="' + Date.parse(date) + '">' + chatSandTimeShow + '</div>' +
				'<div class="service-message-item-box">' +
				'   <div class="service-message-item faqs">' +
				'       <div class="service-message">' +
				'           <p>'+$.i18n.prop('bcb7645e8ed858b49480cd0db35f73f2')+'：</p>' + consultListStr +
				'       </div>' +
				'       <span></span>' +
				'   </div>' +
				'   <div class="clear"></div>' +
				'</div>' +
				'<div class="service-message-item-box">' +
				'   <div class="service-message-item-prompt">' +
				'       <div class="service-message">'+$.i18n.prop('86e8f12d4b73535499be49442cc93501')+'<span class="color_ff6766 cursor_po openOnlineService">'+$.i18n.prop('3333d84ac619f3bd17e651e4c82a400d')+'</span> </div>' +
				'   </div>' +
				'   <div class="clear"></div>' +
				'</div>';

			//经内容写入聊天列表中
			$('.service-message-list-pack .mCSB_container').append(str);
			//滚动到底部
			_this.messageListScrollBottom();
		},
		//十分钟无咨询会话超时
		SetcloseConsultTimer: function(){
			var _this = this;
			clearTimeout(closeConsultTimer);
			closeConsultTimer = setTimeout(function(){
				$.cookie('serviceStatus','off');
				$('.service-box-top-nav-sub .openOnlineService').attr('data-status','off').html($.i18n.prop('3333d84ac619f3bd17e651e4c82a400d'));
				$('.service-message-list-pack .mCSB_container').append('<div class="service-message-item-box">' +
					'   <div class="service-message-item-prompt">' +
					'       <div class="service-message">'+$.i18n.prop('8225db7126459a15cc726a0f774cd55d')+'</div>' +
					'   </div>' +
					'   <div class="clear"></div>' +
					'</div>');
				_this.messageListScrollBottom();
			},600000);
		}
	}


})(jQuery);


$(function () {

	$('.webim-dom').testWebim();


	var height = $(window).height();
	var width = $(window).width();
	// $(".service-box").css({ top: (height-498)/2+'px', left: (width-418)/2+'px'});
	$(".service-box").css({bottom: '68px', right: '230px'});


	// 点击聊天弹窗（推荐房源）、客服弹窗、通知看看或者我的收藏意见反馈,其中一个就将其他的层级降低,自己的提高
	$('.look-notify-box, .im_new_L.im_new_notify,.im_new_L.im_new_collect,.im_new_L.im_new_feedback').click(function () {
		$('.look-notify-box').css('z-index', '1005');
		$('#IM-Chatwin,#recommend-house').css('z-index', '1003');
		$('.service-box').css('z-index', '1000');
	});
	$('.service-box, .im_new_L.im_new_S').click(function () {
		$('.service-box').css('z-index', '1005');
		$('#IM-Chatwin,#recommend-house').css('z-index', '1003');
		$('.look-notify-box').css('z-index', '1000');
	});
	$('#IM-Chatwin, .im_new_L.im_new_M, #recommend-house').click(function () {
		$('#IM-Chatwin, #recommend-house').css('z-index', '1005');
		$('.look-notify-box').css('z-index', '1003');
		$('.service-box').css('z-index', '1000');
	});


	// $('#dialogcanvas').canvasDialog();

	//自定义搜索框
	var opt = {
		input: $('#chan_definegroup .defineselectinput'),
		box: $('#chan_definegroup .defineselectbox'),
		noanimat: true
	}
	defineSelect.init(opt);


	$('.service-box').mouseleave(function (e) {
		var $target = $(e.target);


		$(this).blur();
	})


	//日历控件
	$('.im_clanbox [calender-input="true"]').on('click', function () {

		var $this = $(this), $checkins = $('#clan_start'), $checkouts = $('#clan_end');

		var datatime = $this.attr('data-time') ? $this.attr('data-time') : $checkins.attr('data-time');
		$this.attr('clickActive', '1');
		var $objDom = null;
		if (datatime)
			$objDom = $this;
		else {
			$objDom = $checkins;
			$checkins.attr('clickActive', '1');
			$this.attr('clickActive', '0');
		}

		var left = $objDom.position().left;

		var $im_chanbox = $('.im_clanbox');
		var $calender = $im_chanbox.find('.calendarfixed');
		if ($calender.length == 0) {
			$im_chanbox.append('<div class="calendarfixed" ></div>');
			$calender = $('.im_clanbox .calendarfixed');
		}

		$calender
			.css({'bottom': '70px', 'left': left, 'top': 'auto'})
			.removeAttr('inOrOut oldMonth endMonth').empty();


		var settings = {
			type: 'details',
			invalidDate: $('input[name=invalidDate]').val(),
			invalidChooseDate: $('input[name=invalidChooseDate]').val(),
			minNights: $('input[name=minNights]').val(),
			startMonth: $checkins.attr('data-time') ? $checkins.attr('data-time') : '',
			endMonth: $checkouts.attr('data-time') ? $checkouts.attr('data-time') : '',
			fixedparent: true,
			calMonthlength: $('[name=calMonthlength]').val() || 12,
			unknownDateStr: $('[name=unknownDateStr]').val(),
			callback: Chan_CalendarBack
		};

		if (!$im_chanbox.attr('hasaddLisener')) {
			settings.addLisener = true;
			$im_chanbox.attr('hasaddLisener', '1');
		}

		if ($this.attr('id') == 'clan_end' && datatime)//选择退房日期(没有选择入住日期之前不能选择退房日期)
		{
			settings.inOrOut = false;
			if ($this.attr('data-time')) {
				settings.startMonth = $checkins.attr('data-time');
				settings.endMonth = $this.attr('data-time');
			}

		}
		$calender.appCalendar(settings);
		$('#clan_start').focus();


	})


	function Chan_CalendarBack(param) {//选择日期后的回调函数
		var $checkin = $('#clan_start');
		var $checkout = $('#clan_end');
		$('.calendarfixed').removeAttr('inOrOut oldMonth endMonth startmonth').empty().hide();

		if (param.info) {
			if ($checkin.attr('clickActive'))//日历是由入住文本框触发
			{
				$checkin.val(dataChangeForUse(param.startMonth)).attr('data-time', param.startMonth);
				$checkin.removeAttr('clickActive');
				$checkout.val('').removeAttr('data-time').click();
			}
		} else {
			if (!param.startMonth && !param.endMonth)//是清除按钮
			{
				$checkin.val('').removeAttr('data-time');
				$checkout.val('').removeAttr('data-time');
				$checkin.removeAttr('clickActive');
				$checkout.removeAttr('clickActive');

				$('.detail-owner .priceList').html('');
				$('.detail-owner .priceList-box').addClass('hide');
			}
			else {
				if ($checkin.attr('clickActive'))//日历是由入住文本框触发
				{
					$checkin.val(Chan_dataChangeForUse(param.startMonth)).attr('data-time', param.startMonth);
					$checkin.removeAttr('clickActive');

					if (param.startMonth && !$checkout.attr('data-time'))
						$checkout.click();
					if (parseInt($checkin.attr('data-time')) >= parseInt($checkout.attr('data-time'))) {
						$checkout.val('').removeAttr('data-time').click();
					}
				}
				else {
					$checkout.val(Chan_dataChangeForUse(param.endMonth)).attr('data-time', param.endMonth);
					$checkout.removeAttr('clickActive');
				}

			}
		}

		// 预定框日历同步

		$('#cins').val($checkin.val()).attr('data-time', $checkin.attr('data-time') ? $checkin.attr('data-time') : '');
		$('#couts').val($checkout.val()).attr('data-time', $checkout.attr('data-time') ? $checkout.attr('data-time') : '');
		$('.detail-owner .priceList').html('');
		$('.detail-owner .priceList-box').addClass('hide');
		$('#book_it_disabled_message').attr('errortype', '');
		$('#book_it_disabled_message').html('').addClass('hide');
		history.pushState('', '', location.pathname + '?startDate=' + $checkin.val() + '&endDate=' + $checkout.val());
	}

//将日期进行转换
	function Chan_dataChangeForUse(str) {
		if (!str)
			return '';
		if (str.length == 8) {
			return str.substr(0, 4) + '-' + str.substr(4, 2) + '-' + str.substr(6, 2);
		} else {
			return str.replace('-', '').replace('-', '');
		}
	}


	//滚动条


	// if(navigator.userAgent.indexOf("Window")>0){

	var scrollwidth = getScrollbarWidth();


	var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
	var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
	var isEdge = (userAgent.indexOf("Windows NT 6.1") > -1 && userAgent.indexOf("Trident/7.0") > -1) && (!isIE); //判断是否IE的Edge浏览器
	var webimRight = parseInt($('.webim-dom').css('right').replace('px', ''));
	var lookNotifyRight = parseInt($('.look-notify-box').css('right').replace('px', ''));

	if (navigator.userAgent.indexOf("MSIE") > 0 || isEdge) {
		//是ie浏览器

		//注:以下样式中的数据均取自onehomeWebim.css里面写的对应的元素设定值
		//先添加样式
		if (scrollwidth) scrollwidth = scrollwidth - 1;
		var strwin = '.windowoverstyle{overflow:hidden;padding-right:' + scrollwidth + 'px;}' +    //阻止body滚动且重新设置padding和right以保持页面不晃动
			'.windowoverstyle #webim-dom{ right:' + (webimRight + scrollwidth) + 'px;}' +
			'.windowoverstyle .backArea{ right:' + (webimRight + scrollwidth) + 'px;}' +
			'.windowoverstyle .look-notify-box{right:' + (lookNotifyRight + scrollwidth) + 'px}';
		var t = document.createStyleSheet();
		t.cssText = strwin;
	} else {

		var strwin = '.windowoverstyle{overflow:hidden;padding-right:' + scrollwidth + 'px;}' +
			'.windowoverstyle #webim-dom{ right:' + (webimRight + scrollwidth) + 'px;}' +
			'.windowoverstyle .backArea{ right:' + (webimRight + scrollwidth) + 'px;}' +
			'.windowoverstyle .look-notify-box{right:' + (lookNotifyRight + scrollwidth) + 'px}';
		var r = document.createElement("style");
		r.setAttribute("type", "text/css");
		document.getElementsByTagName('head')[0].appendChild(r);
		if (r.styleSheet) {
			r.styleSheet.cssText = strwin;
		} else {
			r.appendChild(document.createTextNode(strwin));
		}

	}

	// 判断是否存在滚动条
	function ifscroll() {
		return document.documentElement.offsetHeight > document.documentElement.clientHeight;
	}
})

// 判断图片是否存在,不存在使用默认图
function onImgErr(e) {
	var img = event.srcElement;
	img.src = "/images/pic_default_image.png";
	img.onerror = null;
}


function dialogOption(obj) {
	try {
		var $this = obj;


		var $this = obj;
		if ($this.attr("lock") === "false") {
			var $win = $('#IM-Chatwin');
			$this.attr("lock", "true");
			if ($win.css('display') == 'block') { //原本是可见,要做隐藏

				var $im_ul_wrapper = $('#im_ul_wrapper');
				var currentTop = $im_ul_wrapper.find('.mCustomScrollBox').children('.mCSB_container').css('top');
				if (currentTop) {

					$im_ul_wrapper.attr('data-scroll-top', currentTop);
				}


				$win.hide();

				$this.attr("lock", "false");
				$('.im_L.im_M').removeClass('open');

				// 聊天窗口关闭，推荐房源窗口也关闭
				$('.recommend-house').hide();
			} else {

				var $im_ul_wrapper = $('#im_ul_wrapper');

				var currentTop = $im_ul_wrapper.attr('data-scroll-top');

				if (currentTop)
					$im_ul_wrapper.find('.mCustomScrollBox').children('.mCSB_container').css('top', currentTop);

				//显示
				$win.show();
				$this.attr("lock", "false");

				// $this.removeClass('folded');
				$('.im_L.im_M').addClass('open');


				var $msgcontent = $win.find('.msg-content:visible');
				$msgcontent.find('.mCustomScrollbar').mCustomScrollbar('scrollTo', "bottom", {scrollInertia: -400});

			}
		}
	}
	catch (e) {
		console.log(e);
	}
}


//判断图片是否加载完成

var t_img; // 定时器
var isLoad = true; // 控制变量

// 判断图片加载的函数
function isImgLoad(imgs, callback) {
	// 注意我的图片类名都是cover，因为我只需要处理cover。其它图片可以不管。
	// 查找所有封面图，迭代处理
	imgs.each(function () {
		// 找到为0就将isLoad设为false，并退出each
		if (this.height === 0) {
			isLoad = false;
			return false;
		}
	});
	// 为true，没有发现为0的。加载完毕
	if (isLoad) {
		clearTimeout(t_img); // 清除定时器
		// 回调函数
		callback();
		// 为false，因为找到了没有加载完成的图，将调用定时器递归
	} else {
		isLoad = true;
		t_img = setTimeout(function () {
			isImgLoad(imgs, callback); // 递归扫描
		}, 500); // 500毫秒就扫描一次，可以自己调整
	}
}


/***以下是关闭或打开聊天窗的动画效果   已弃用****/


/**
 * 绘制形状
 * @param s1 {Number} 起点一
 * @param s2 {Number} 起点二
 * @param p1 {Number} 结束点一
 * @param p2 {Number} 结束点二
 */
function draw(s1, s2, p1, p2) {
	ctx.clearRect(0, 0, canvas.width, canvas.height);
	ctx.beginPath();
	ctx.moveTo(s1, 0);
	ctx.bezierCurveTo(s1, canvas.height * 0.2, p1, canvas.height * 0.6, p1, canvas.height);
	ctx.lineTo(p2, canvas.height);
	ctx.bezierCurveTo(p2, canvas.height * 0.6, s2, canvas.height * 0.2, s2, 0);
	ctx.lineTo(s1, 0);
	//ctx.fillStyle = "rgba(f, f, 0, .2)";
	ctx.fillStyle = "#dcdcdc";
	ctx.fill();
}

/**
 * 擦除方式
 * @param y {Number}
 * @param speed {Number}
 * @param type 类型，放大或缩小 zoomin、zoomout
 */
function clearRect(y, speed, type) {
	if (type === "zoomout") {
		ctx.clearRect(0, y, canvas.width, speed);
	} else if (type === "zoomin") {
		ctx.clearRect(0, 0, canvas.width, y);
	}
}

/**
 * 缩放效果
 * @param s1 {Number} 起点一
 * @param s2 {Number} 起点二
 * @param p1 {Number} 结束点一
 * @param p2 {Number} 结束点二
 * @param type {String} 类型，放大或缩小 zoomin、zoomout
 */
function scale(s1, s2, p1, p2, type, callback) {

	var dist1 = Math.abs(p1 - s1);
	var dist2 = Math.abs(p2 - s2);
	var d1, d2, _p1, _p2, speed1, y, speed2;
	if (dist1 === 0 || dist2 === 0) {
		dist1 = 1;
		dist2 = 1;
	}
	speed1 = 200;
	speed2 = 200;
	if (type === "zoomout") {
		d1 = (p1 >= s1 && p1 < speed1) ? 0 : p1 < s1 ? -speed1 : speed1;
		d2 = p2 < s2 ? -speed1 * dist2 / dist1 : speed1 * dist2 / dist1;
		_p1 = s1;
		_p2 = s2;
		y = 0;
		var t = setInterval(function () {
			if (_p2 - _p1 <= p2 - p1) {
				clearInterval(t);
				var timer = setInterval(function () {
					if (y > canvas.height) {
						clearInterval(timer);
						callback && callback();
					}
					clearRect(y, speed2, type);
					y += speed2;
					speed2 += 1;
				}, 17);
			}
			draw(s1, s2, _p1, _p2);
			_p1 += d1;
			_p2 += d2;
			if ((d1 < 0 && _p1 <= p1) || (d1 > 0 && _p1 >= p1)) {
				_p1 = p1;
			}
			if ((d2 < 0 && _p2 <= p2) || (d2 > 0 && _p2 >= p2)) {
				_p2 = p2;
			}
		}, 17);
	} else if (type === "zoomin") {
		d1 = (p1 >= s1 && p1 < speed1) ? 0 : p1 < s1 ? speed1 : -speed1;
		d2 = p2 < s2 ? speed1 * dist2 / dist1 : -speed1 * dist2 / dist1;
		_p1 = p1;
		_p2 = p2;
		y = canvas.height;
		var timers = setInterval(function () {
			if (y <= 0) {
				clearInterval(timers);
				var t = setInterval(function () {
					if (_p2 - _p1 >= s2 - s1) {
						clearInterval(t);
						callback && callback();
					}
					draw(s1, s2, _p1, _p2);
					_p1 += d1;
					_p2 += d2;
				}, 17);
			}
			draw(s1, s2, _p1, _p2);
			clearRect(y, speed2, type);
			y -= speed2;
			speed2 += 1;
		}, 17);
	}


}


function getScrollbarWidth() {
	if (document.documentElement.offsetHeight > document.documentElement.clientHeight) {
		var oP = document.createElement('p'),
			styles = {
				width: '100px',
				height: '100px',
				overflowY: 'scroll'
			}, i, scrollbarWidth;
		for (i in styles) oP.style[i] = styles[i];
		document.body.appendChild(oP);
		scrollbarWidth = oP.offsetWidth - oP.clientWidth;
		oP.remove();
		return scrollbarWidth;
	} else {
		return 0;
	}
}


function array_remove_repeat(arr) { // 去重
	try {
		var r = [];
		for (var i = 0; i < arr.length; i++) {
			var flag = true;
			var temp = arr[i].id;
			for (var j = 0; j < r.length; j++) {
				if (temp === r[j].id) {
					flag = false;
					break;
				}
			}
			if (flag) {
				// r.push(temp);  // 只是将id传入了数组
				r.push(arr[i]);   // 这里传入的是整个对象
			}
		}
		return r;

	} catch (e) {
		return arr;
	}
}


function insertDomforAfter(id, dom, parentDom) {//根据id确定插入的顺序,前提是id标号有规律
	if (!id || !dom || !parentDom)
		return;
	$talk_timelist = parentDom.find('.talk_time');
	if ($talk_timelist.length == 0) {
		parentDom.find('.mCustomScrollBox>.mCSB_container>div').append(dom);
	}
	else {

		var flag = false;

		for (var i = $talk_timelist - 1; i >= 0; i--) {
			var $this = $talk_timelist.eq(i);
			var tempid = $this.attr('id');
			if (id > tempid) {
				flag = true;
				$this.next().after($(dom));
				break;
			}
		}
		if (!flag) {
			parentDom.find('.mCustomScrollBox>.mCSB_container>div').prepend(dom);
		}
	}
}

function ifrepeat(id, Arr) {//判断数组中是否已有此数据
	var flag = false;
	if (!id || !Arr) {
		return false;

	}

	for (var i = 0; i < Arr.length; i++) {
		if (id == Arr[i].id) {//有重复数据
			flag = true;
		}
	}
	return flag;

}

function getNowTime() {
	var date = new Date();
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
	var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
	var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
	var currentDate = date.getFullYear() + '-' + month + '-' + strDate + ' ' + hour + ':' + minute + ':' + seconds;
	return currentDate;
}














